2013-04-27 101 views
0

我知道你可以得到類Texture2d的寬度和高度,但爲什麼你不能得到x和y座標?我必須爲它們創建單獨的變量嗎?看起來像很多工作。Texture2d的座標?

+0

Texture2D只是一個紋理,它在遊戲中沒有位置。您必須創建一個類或結構來處理位置和紋理。 – Cyral 2013-04-27 15:08:44

回答

1

您必須使用Vector2對象與Texture2D對象關聯。 A Texture2D -object本身沒有任何座標。
當您想繪製紋理時,需要使用SpriteBatch來繪製紋理,而這需要Vector2D來確定座標。

public void Draw (
    Texture2D texture, 
    Vector2 position, 
    Color color 
) 

這是從MSDN拍攝。

所以,可以創建一個struct

struct VecTex{ 

    Vector2 Vec; 
    Texture2D Tex; 

} 

,或者當您需要進一步處理的類。

1

單獨的Texture2D對象沒有任何屏幕x和y座標。
爲了在屏幕上繪製紋理,您必須使用Vector2或矩形設置其位置。

下面是一個使用Vector2一個例子:

private SpriteBatch spriteBatch; 
private Texture2D myTexture; 
private Vector2 position; 

// (...) 

protected override void LoadContent() 
{ 
    // Create a new SpriteBatch, which can be used to draw textures. 
    spriteBatch = new SpriteBatch(GraphicsDevice); 

    // Load the Texture2D object from the asset named "myTexture" 
    myTexture = Content.Load<Texture2D>(@"myTexture"); 

    // Set the position to coordinates x: 100, y: 100 
    position = new Vector2(100, 100); 
} 

protected override void Draw(GameTime gameTime) 
{ 
    spriteBatch.Begin(); 
    spriteBatch.Draw(myTexture, position, Color.White); 
    spriteBatch.End(); 
} 

下面是使用矩形的例子:

private SpriteBatch spriteBatch; 
private Texture2D myTexture; 
private Rectangle destinationRectangle; 

// (...) 

protected override void LoadContent() 
{ 
    // Create a new SpriteBatch, which can be used to draw textures. 
    spriteBatch = new SpriteBatch(GraphicsDevice); 

    // Load the Texture2D object from the asset named "myTexture" 
    myTexture = Content.Load<Texture2D>(@"myTexture"); 

    // Set the destination Rectangle to coordinates x: 100, y: 100 and having 
    // exactly the same width and height of the texture 
    destinationRectangle = new Rectangle(100, 100, 
             myTexture.Width, myTexture.Height); 
} 

protected override void Draw(GameTime gameTime) 
{ 
    spriteBatch.Begin(); 
    spriteBatch.Draw(myTexture, destinationRectangle, null, Color.White); 
    spriteBatch.End(); 
} 

的主要區別在於,通過使用矩形你可以擴展你的紋理,以適應目標矩形的寬度和高度。

您可以在MSDN找到更多關於SpriteBatch.Draw方法的信息。