Beginning Math and Physics for Game Programmers

 <  Day Day Up  >  

On the CD-ROM, you will find a demo named Circles. Here's a brief description from the programmer:

This example is used to demonstrate the movement and collision of two circles with the bounds of the screen and each other. The circles are placed in random positions on the screen and are given random directions to travel in. To maintain simplicity, true vector reflection is not used for the collision of the balls. Instead, a basic reflection algorithm is used to maintain the appearance of true reflection .

” Dustin Henry

Go ahead and run the demo by double clicking circles.exe. You'll see the two balls bounce around and occasionally collide with each other. Behind the scenes, the computer is checking frame by frame to see if they have hit each other using the circle-circle collision method described in the preceding section.

You can view the source code by double-clicking circles_code.txt. If you scroll down far enough, you'll see the section responsible for the circle-circle collision detection, which is shown in Listing 2.1.

Listing 2.1. Circle-Circle Collision

////////////////////////////////////////////////////////////////// // checkBallCollision : Check for a collision with another ball // // In : ball2 - the ball to check collision with // // Return : True if there was a collision with another ball ////////////////////////////////////////////////////////////////// bool Ball::checkBallCollision(Ball &ball2) { // The radius of the balls int radius1 = diameter / 2; int radius2 = ball2.diameter / 2; // The center point of the first ball POINT center1; center1.x = radius1 + bounds.left; center1.y = radius1 + bounds.top; // The center point of the second ball POINT center2; center2.x = radius2 + ball2.bounds.left; center2.y = radius2 + ball2.bounds.top; // The distance between the two balls' centers double distance = sqrt(SQUARE(center2.x - center1.x) + SQUARE(center2.y - center1.y)); // See if they have collided if (distance <= radius1 + radius2)

You might notice that as a bonus the programmer has also included collision detection between the balls and the edge of the screen. This uses a bounding-box approach to collision detection, because the screen is made up of four straight lines.

You might want to revisit this demo after reading Chapter 14, "Rotational Motion," which discusses collision response.

 <  Day Day Up  >  

Категории