XNA GameStudio 2.0
Bat & Ball Collisions

Adjusting Bat/Ball Classes

When the ball touches one of the bats, we say that a collision has occurred. First go to the Bat.cs class that you wrote earlier - we are going to put some code in here to help us.

public Rectangle BatRect
{
   get { return new Rectangle((int)position.X, (int)position.Y, sprite.Width, sprite.Height); }
}

This is called a property - it creates a rectangle to describe the coordinates and dimensions of the bat at any time in the game.

We need to do the same for the ball. The following code goes into the Ball.cs class.

public Rectangle BallRect
{
   get { return new Rectangle((int)position.X, (int)position.Y, sprite.Width, sprite.Height); }
}

Adding To The Game Update Routine

In the previous section, you added code to the Update() method of the main game class. This code was to keep the ball on screen. We need to add a few more lines underneath the last things we wrote.

if (player1.BatRect.Contains(ball.BallRect))
{
   ball.velocity.X *= -1.0f;
}
if (player2.BatRect.Contains(ball.BallRect))
{
   ball.velocity.X *= -1.0f;
}

This code works in a similar way to the code that makes the ball bounce off the top or bottom of the screen.

Compile and test your code to make sure that ball now bounces off the bat. We will add some more control for the players in the next section. For now, just check that things work as expected and make any minor adjustments to the speed of the ball that you think are necessary.