Let's Move
Drawing different sort modes and layer depths is fun and all, but it really isn't all that exciting. Now, let's make the two images that you've drawn move and bounce off the edges of the screen. To move the objects, you are going to need to change the positions at which they are drawn. Right now, they are both being drawn at constant positions, one with its top-left corner at the exact center of the window and the other offset from the center so that the image itself is centered in the middle of the screen.
Tip
The code for this section of the chapter is available with the source code for the book under Chapter 2 and is entitled MovingSprites.
To move something around the screen, you have to modify the position of that
object between frames. Therefore, the first thing you need to do is start using a
variable in place of the constant values you've been using to specify the objects'
positions. Add two class-level Vector2
variable
definitions (called pos1
and pos2
) at the top of your class, and initialize both
objects to Vector2.Zero
:
Vector2 pos1 = Vector2.Zero; Vector2 pos2 = Vector2.Zero;
You'll also need to have a speed variable for each object. This variable will be
used to determine how far you move each object between frames. Add two float
variables (called speed1
and speed2
) below the
Vector2
variables you just added:
float speed1 = 2f; float speed2 = 3f;
Now, change the position parameters in each Draw
method to use pos1
and
pos2
, respectively. Just to clean things up, ...
Get Learning XNA 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.