- XNA - Intro :
- XNA Setup :
- The Game Loop :
- State Machines :
- 2D Starter - part 1 :
- 2D Starter - part 2 :
- 2D Starter - part 3 :
- 2D Starter - part 4 :
XNA Development - A 2D Game Starter - part 3
Next, we'll modify the ship class to move using velocity. We'll do this by adding a velocityX and velocityY variable to our class. Any player movement will modify this which will then update the ships position. To keep our ship from shooting all over the place we'll add a 'drag' that slows the ship and a maximum velocity. Lastly we'll add some bounds checking. If the ship hits the borders of the screen, we'll either wrap around to the other side, bounce off or come to a dead stop.
Arrow keys move the ship, space bar resets the ship to 10,10, the enter key changes the behavior at the screen edges and the X key toggles the drag on the ship.
The key changes to the code are in the Update methods of the Game class and the Ship class. The Game class now calls calls the Update method of the ship after getting player input. It then calls a new function in the Ship class to check to see if the ship hit the screen edge. The update code in Game1.cs now looks like this:
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
getInput();
playerShip.Update(gameTime);
playerShip.CheckBounds(bounds);
base.Update(gameTime);
}
In the getInput method of Game1.cs we'll now check for the arrow keys and call the ships Move function. We'll define an amount for the ship to move each time, in this case 0.125... If the player holds a key in a given direction, this will build until the max velocity is reached. By changing the maxVelocity, we change the top speed; increasing the amount we increase velocity each time changes the acceleration. Part of the getInput method from Game1.cs follows.
{
float deltaX, deltaY;
deltaX = 0f;
deltaY = 0f;
kb = Keyboard.GetState();
if (kb.IsKeyDown(Keys.Escape))
this.Exit();
if (kb.IsKeyDown(Keys.Up))
{
deltaY -= step;
}
if (kb.IsKeyDown(Keys.Down ))
{
deltaY += step;
}
if (kb.IsKeyDown(Keys.Left))
{
deltaX -= step;
}
if (kb.IsKeyDown(Keys.Right))
{
deltaX += step;
}
playerShip.Move(deltaX, deltaY);
if (kb.IsKeyDown(Keys.Space))
{
playerShip.MoveTo(10, 10);
}
...
The source for this one: here.
