I'm completely fresh to game development and came up to a problem which I'm not sure how to solve. I have textures which are quite too big for screen. So i used SpriteBatch.Method which uses rectangle as parameter which allows me to get custom size of texture. But I need as well Vector position for movement to specific direction. So I used method which uses Vector position and float scale to make it smaller. And now I can't check really if it Intersects with other objects or simple width, height properties. It seems that I cannot pass both vector position and rectangle as well. Isn't there a way to specify just a rectangle for texture's height/width to be rendered and vector for position?
-
\$\begingroup\$ Your drawing and game logic should be separated. Your draw loop should adapt to the way your objects are represented. If your game objects are rectangles- find a way the drawing can accomodate that. As @Paste answered there are overloads that do exactly as you need (even one that takes a source rect and destination rect as parameters). \$\endgroup\$– FelsirCommented Apr 17, 2016 at 10:06
2 Answers
There are three overloads of the SpriteBatch.Draw()
method available that will suit you:
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color, Single, Vector2, Single, SpriteEffects, Single)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color, Single, Vector2, Vector2, SpriteEffects, Single)
In each case, the second parameter is a Vector2
representing the location on the screen where the texture should be drawn, and the third parameter is a (nullable) Rectangle
that represents the portion of the texture to be drawn. You can read more about them at the MSDN page.
If the rectangle is where you want the picture to be drawn (destination rectangle), rather than the part of the texture you wish to draw (source rectangle), then a better answer would be to recreate the rectangle whenever the object moves using the vector2.
For example:
//movement code here
rectangle = new Rectangle((int)position.x, (int)position.y, width, height);
That will put the position vector2 in the top left hand corner. You can put it in the centre by:
rectangle = new Rectangle(
(int)(position.x - (width/2)),
(int)(position.y - (height/2)), width/2, height/2);