Chicken Pong – Part 1

August 30, 2011

I worked on my first 2d xna project recently and decided a postmortem would be a good first post for this blog. There’s plenty of 2d xna hello world examples out there so I’m not going to go into a lot of extraneous detail in this post. I’m mostly going to focus on the ideas behind getting my first project up and running.

Here’s the final product.

My first goal was to load a sprite and move it around the screen. The general idea is pretty simple, load a texture, update it’s position every game cycle and then render it at that position.

Texture2D ChickenTexture;
Vector2 ChickenPosition;
Vector2 ChickenSpeed;

The first step was to grab an image from google image search to use for my texture. I settled on a chicken (fun fact a google image search for ‘chicken’ mostly comes up with chicken-the-food so I had to go with ‘hen’ instead). I added it to the content project and loaded it into a property for use in the game in LoadContent().

protected override void LoadContent()
{
   ChickenTexture = Content.Load<Texture2D>("Chicken");
}

To render it, I used the texture and position with SpriteBatch.Draw() in Draw().

protected override void Draw(GameTime gameTime)
{
   GraphicsDevice.Clear(Color.Orange);

   SpriteBatch.Begin();
   SpriteBatch.Draw(ChickenTexture, ChickenPosition, Color.White);
   SpriteBatch.End();
}

A static sprite isn’t very useful, so the next step was to get that chicken animated. Animating was as simple as updating the sprite’s position every game cycle in Update() by adding the speed property to the position.

protected void Update(GameTime gameTime)
{
   ChickenPosition += ChickenSpeed;
}

Of course that lead to the sprite leaving the screen pretty quickly so I reversed the x or y component of speed as position reached zero or the width/height of the viewport and ended up with a chicken that bounced around the screen.

protected void Update(GameTime gameTime)
{
   if (ChickenPosition.X + ChickenTexture.Width > graphics.GraphicsDevice.Viewport.Width || ChickenPosition.X < 0)
   {
      ChickenSpeed.X *= -1;
   }
   if (ChickenPosition.Y + ChickenTexture.Height > graphics.GraphicsDevice.Viewport.Height || ChickenPosition.Y < 0)
   {
      ChickenSpeed.Y *= -1;
   }
   ChickenPosition += ChickenSpeed;
}

When I started this project, I intended to move on to updating the sprite location based on user input but that bouncing motion reminded me of Pong so I decided to turn it into a full fledged game.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s