Game Development Reference
In-Depth Information
the center of game objects, let's use them to calculate the distance between the ball and a paint
can, as follows:
var ball = Game.gameWorld.ball;
var distance = ball.position.add(ball.center).subtractFrom(this.position)
.subtractFrom(this.center);
Now that you've calculated this vector, you have to check whether 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 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, you
can say that the ball collides with the can. You can write an if instruction that checks this condition:
if (Math.abs(distance.x) < this.center.x &&
Math.abs(distance.y) < this.center.y) {
// handle the collision
}
You use the Math.abs method to calculate the absolute value of the distance components. If there
is a collision between the ball and the can, you need to change the color of the can to the color of
the ball.
Next, you have to reset the ball so it can be shot again. The following two instructions do exactly that:
this.color = ball.color;
ball.reset();
You can try out the Painter7 example to see that collisions between the ball and the paint cans are
properly handled.
As you've probably noticed, the collision-detection method used here isn't very precise. In Chapter 26,
you see a better way of dealing with collisions on a per-pixel level, although this does make your
game run more slowly if you don't watch out.
Note In the end, simple lines of code like the ones written in this section make all the difference in the
player experience. As you build up your game application, you'll find that sometimes the littlest thing to the
player took the longest to program, and the biggest changes were achieved with only one or two lines!
What You Have Learned
In this chapter, you have learned:
How to add properties to your classes
How to handle basic collisions between game objects
How to define game objects that have different colors
 
 
Search WWH ::




Custom Search