2013-04-27 29 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方法的信息。