Game Development Reference
In-Depth Information
8.4 Handling Collisions Between the Ball and the Cans
In the Painter7 program, we have extended the example by also handling collisions
between the ball and the cans. If two objects collide, we have to handle this collision
in one of the two object's Update method. In this case, we can choose to handle colli-
sions in the Ball class or in the PaintCan class. We have chosen to handle the collision
in the PaintCan class, because if we were to do it in the Ball class, we would need to
repeat the same code three times, one for each paint can. By handling collisions in
the PaintCan class, we get this behavior automatically, since each can will check for
itself if it collides with the ball.
Although collision checking can be done in many different ways, we are going
to use a very simple method here. We define that there is a collision between two
objects if the distance between their centers is smaller than a certain value. The po-
sition of the center of the ball at any time in the game world is computed by adding
the center of the ball sprite to the position of the ball. Similarly, the center of the
paint can we are currently updating is given by position + Center . Therefore we can
calculate a vector expressing the distance as follows:
Vector2 distanceVector = (Painter.GameWorld.Ball.Position
+ Painter.GameWorld.Ball.Center)
(position + Center);
Note that not all the parentheses are obligatory (which ones are not?). We wrote
them here, so that it is clear what we are doing. Now that we have calculated this
vector, we have to check if its length in both the x and y directions is smaller than
some given value. If the absolute value of the x component of the distance vector is
smaller than the x value of the center, it means that the ball object is within the x
range of the can. The same principle holds for the y direction. If this holds for both
the x and y components, we can say that the ball collides with the can. We can write
an if -instruction that checks this condition:
if (Math.Abs(distanceVector.X) < Center.X && Math.Abs(distanceVector.Y) < Center.Y)
{
Handlethecollision.
}
We use the Math.Abs method to calculate the absolute value. If there is a collision
between the ball and the can, we need to change the color of the can to the color of
the ball. Next, we have to reset the ball so that it can be shot again. The following
two instructions do exactly that:
Color = Painter.GameWorld.Ball.Color;
Painter.GameWorld.Ball.Reset();
The full Painter7 example is again available in the solution provided with this chapter.
Search WWH ::




Custom Search