0

我知道你可以得到 class 的宽度和高度Texture2d,但是为什么你不能得到 x 和 y 坐标呢?我是否必须为它们创建单独的变量或其他东西?似乎工作量很大。

4

2 回答 2

1

单独的 Texture2D 对象没有任何屏幕 x 和 y 坐标。
为了在屏幕上绘制纹理,您必须使用 Vector2 或 Rectangle 设置它的位置。

这是一个使用 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();
}

这是一个使用 Rectangle 的示例:

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();
}

主要区别在于,通过使用 Rectangle,您可以缩放纹理以适应目标矩形的宽度和高度。

您可以在MSDN上找到有关 SpriteBatch.Draw 方法的更多信息。

于 2013-04-28T16:45:07.277 回答
1

您必须将Vector2-object 与 -object 关联使用Texture2D。A Texture2D-object 本身没有任何坐标。
当您要绘制纹理时,您需要 aSpriteBatch来绘制它,而这需要 aVector2D来确定坐标。

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

这取自MSDN

所以,要么创建一个struct

struct VecTex{

    Vector2 Vec;
    Texture2D Tex;

}

或需要进一步处理的课程。

于 2013-04-27T08:12:19.863 回答