Game Development Reference
In-Depth Information
5.2.3 Changing the Origin of a Sprite
When you run the Balloon1 example, you will notice that the balloon is drawn such
that the top left corner of the sprite is at the current mouse position. When we draw
a sprite at a certain position, the default behavior is that the top left corner of the
sprite is drawn at that position. If we execute the following instruction:
spriteBatch.Draw(someSprite, somePosition, Color.White);
the sprite named someSprite is drawn on the screen such that its top left corner is at
position somePosition . You could also call the top left corner of the sprite the origin
of the sprite. So what if we want to change this origin? For example, suppose that we
would like to draw the center of the sprite someSprite at position somePosition ? Well,
we could calculate that by using the Width and Height properties of the Texture2D type.
Let us declare a variable called origin and store the center of the sprite inside it:
Vector2 origin = new Vector2(someSprite.Width / 2, someSprite.Height / 2);
Now if we want to draw the sprite someSprite with this different origin we can do
that as follows:
spriteBatch.Draw(someSprite, somePosition
origin, Color.White);
By subtracting the origin from the position, the sprite is drawn at an offset such that
the position somePosition indicates the center of the sprite. The spriteBatch object also
has a method for drawing a sprite using a different origin. This method is also called
Draw , but it has more parameters than the Draw method we have been using until
now. Here is an example of how to call this method:
spriteBatch.Draw(someSprite, somePosition, null , Color.White,
0.0f, origin, 1.0f, SpriteEffects.None, 0);
 
Search WWH ::




Custom Search