Tuesday, October 07, 2008

XNA Part 3 - Updating an Object

Now that we have put a graphic on the screen, we want to make it do something. Perhaps we want to make it move on the screen. First off, in the last example we created a variable inside the Draw method to hold the position of our image. This wont do, because we need to update that value. If we leave it inside the Draw function, it gets recreated every time draw is called. So instead, lets move it out to be a class member of our game class. Just under our declaration of Texture2D alien, we will add

Vector2 position = Vector2.Zero;

This will create a variable accessible to our game class the can persist through our game. We also need to remove the Vector2 line from the draw function. This will also initialize our position to 0,0.

Now in the initialize method, lets set our initial position.

position.Y = graphics.GraphicsDevice.Viewport.Height / 2;

This sets the Y (vertical component) to 1/2 the height our game's viewport, which we access through the graphics.GraphicsDevice.Viewport object. We will leave the X component alone for now. You can run the program to see what you have accomplished so far. The top left corner of your image should be at (0, 1/2 window height)

Now lets move the image in time. To do this we alter the position variable during the update method call. Lets move our image on a sine wave for kicks. Inside the update method, right above base.Update(gameTime); add some code to update our position

position.X += 0.15f;

position.X is a float so we will add 0.15f to its current value;

position.Y = position.Y + (float)Math.Sin(position.X);

Here we take position.Y and add the Sine of the X component. Sin() returns a double, so we need to cast it to a float and add it to Y so that we end up with a float to assign to position.Y.

Now if you run your program your image should oscillate up and down as it wiggles from left to right.
Post a Comment