Sunday, January 16, 2011

XNA Game Development Tips and Tricks 6: 2D Collision Detection make easy for player

We will see how we can do the collision detection and how we can make it a bit easier for the player. Collision detection is one of the most discussed part of game development. Now lets say we have two sprites moving in our game and we want to detect whenever they collide with each other.

What we have here is Sprite’s X and Y Coordinates and its Width and Height. So we will be taking both sprite’s X and Y coordinates and Width and Height and figure out whether both intersects with each other or not. Let’s take a look at the following code:

public bool CheckCollision(Rectangle sourceRect, Rectangle destRect)
{
      return sourceRect.Intersects(destRect);
}

Above code does a perfect collision detection, but there is a little problem with player. We should be giving a little freedom to player so that game does not become very difficult for player. In order to do that we are going to Inflate the Sprite.. dont worry this inflation is only logical and will not be displayed to user.

public bool CheckCollision(Rectangle sourceRect, Rectangle destRect)

      sourceRect.Inflate(5, 5);
      return sourceRect.Intersects(destRect);
}

By Inflating we are inflating one of the Sprite by 5x5. We can Inflate both Sprites as well. Depending on how easy you would want game to be you can decide how much sprite you would like to Inflate.

Sunday, January 9, 2011

XNA Game Development Tips and Tricks 5: Animate 2D Sprites

Animation is very important part of game development, if your game does not have any kind of animation it will look very dull.

While doing animation we have to consider many aspects of the game:

  1. Animation should not be Slower
  2. Animation should be not be Faster
  3. Animation should be Smoother
  4. Animation should load Faster

We will be using following image for the animation:

256x32

If you look at above image, it is single image and not 8 tanks. Reason why we are not having 8 different images and loading them in the game is because it will take more time compared to having single long image loaded. If you have just one single sprite in your game for animation it will not make any difference, but if you have many sprites to be animated you will see significant performance difference. So let us see how we can animate the sprite and how we can control frame rates for the sprite.

First we will declare all required variables to be use.

private int FrameCount = 8; //number of frames in image
private int CurrentFrame = 0; //current frame to display
private float FrameLength = 0.12f; //Frame length per frame.. calculated 1/8 i.e. one second divided by number of frames (8)
private float FrameTimer = 0.0f; //Keep note of time

Now let’s load the content in memory, and add image to the Content project.

mSpriteTexture = Content.Load<Texture2D>(“bluetank”);

now, lets write Update code, which will update the current frame number which we would want to show to the user. Code which we have written in Update method will render 8 Frames in a second.

public void Update(GameTime gameTime)
        {
            FrameTimer += (float)gameTime.ElapsedGameTime.TotalSeconds; //Find out the CurrentTimer and based on this we will calculate which Frame to render.

            if (FrameTimer > FrameLength)
            {
                FrameTimer = 0.0f; //Reset FrameTimer to 0
                CurrentFrame = (CurrentFrame + 1) % FrameCount;  //Set CurrentFrame
            }
        }

Finally draw the sprite on the screen with the updated Frame.

theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(CurrentFrame * 26, 0, 26, mSpriteTexture.Height), Color.White);

Once you write above code, build it, run it and you should be able to see Your Sprite Animating.

Saturday, January 1, 2011

XNA Game Development Tips and Tricks 4: Forcing and Calculating Frame Rates

Happy New Year 2011 to everyone.

We are going to see how we can control Frame Rates and how we can calculate current Frame rate at which game is getting rendered.

Frame rates are very very important part of game, actually speaking frame rats are important in every aspect of not just games but also in life.

Frame rates in video games means rate at which images are being rendered on the screen known as FPS (Frames Per Second). If you do not set correct FPS for game,  gamers will have weird experiences. For example lower Frames Per Second (FPS) will not give them illusion of motion and it will affect the user’s interaction with the game. Today games lock their frame rates to give a steady performance. If you have slower device game frame rates will drop and if you have very high end device game frame rates will increase and may give bad experience to players. Locking Frame Rates will make sure Frame Rates does not go beyond particular point, but we will not be able to control Low Frame Rates much because Low Frame Rates are very much dependent on the resources available.

Link will give you good examples at Frame Rate Samples : http://spng.se/frame-rate-test/

Windows Phone 7 forces 30 FPS, so whenever you create game for Windows Phone 7, you will see one line of code:

TargetElapsedTime = TimeSpan.FromTicks(333333);

if you increase Ticks from 333333 to 666666 you will notice decrease in Frame Rates, and if you decrease Ticks from 333333 to 111111 you will notice increase in Frame Rates. On Windows Phone 7 you will not get higher frame rates, because Windows Phone 7 OS forces 30 FPS, but on Console or PC you will see increase in Frames if your device is capable of doing so.

Now let us look at how we can calculate frames. Write following code in Class declaration.

float CumulativeFrameTime;
int NumFrames;
int FramesPerSecond;
SpriteFont msgFont;

Write following code in LoadContent method.

msgFont = Content.Load<SpriteFont>("score");

Write following code in Draw method.

CumulativeFrameTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000f;
NumFrames++;
if (CumulativeFrameTime >= 1f)
{
    FramesPerSecond = NumFrames;
    NumFrames = 0;
    CumulativeFrameTime -= 1f;
}
spriteBatch.DrawString(msgFont, "FPS: " + FramesPerSecond.ToString(), new Vector2(0, 0), Color.Black);

Above code will calculate FPS and display it on the screen, it is very useful when you are developing game to see, at what point of time your game is dropping FPS and how you can improve on that and many other things.