Johnny Davidson
Johnny Davidson

Reputation: 1

Coordinates of a Texture2d?

I know you can get the width and height of class Texture2d, but why can't you get the x and y coordinates? Do I have to create separate variables for them or something? Seems like a lot of work.

Upvotes: 0

Views: 444

Answers (2)

Felipe Borgiani
Felipe Borgiani

Reputation: 51

A Texture2D object alone doesn't have any screen x and y coordinates.
In order to draw a texture on the screen, you must either set it's position by using a Vector2 or a Rectangle.

Here's an example using 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();
}

And here's an example using 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();
}

The main difference is that by using a Rectangle you are able to scale your texture to fit the destination rectangle's width and height.

You can find some more information about the SpriteBatch.Draw method at MSDN.

Upvotes: 1

bash.d
bash.d

Reputation: 13207

You must use a Vector2-object in association with a Texture2D-object. A Texture2D-object itself does not have any coordinates.
When you want to draw a texture, you will need a SpriteBatch to draw it, whereas this takes a Vector2D to determine the coordinates.

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

This is taken from MSDN.

So, either create a struct

struct VecTex{

    Vector2 Vec;
    Texture2D Tex;

}

or a class when you need further processing.

Upvotes: 1

Related Questions