|
Author
|
||||
|
Related articles
|
||||
|
More in Development
|
||||
This article originally appeared in Dev.Mag Issue 28, released in January 2009
Almost every video game needs to respond to objects touching each other in some sense, a practice commonly known as collision detection. Whether it's simply to prevent the player character from walking through the walls of your maze with a simple collision grid array, or if it's to test if any of the hundreds of projectiles fired by a boss character in a top-down shoot-'em-up have struck the player's ship, your game will likely require a collision detection system of one sort or another.
So there comes a time in almost every game's development cycle when an important choice needs to be made: how accurate should the collision detection be, and which method should be used to achieve that accuracy. This is a decision that is not made lightly, since it can drastically affect both gameplay and performance of your game.
Unfortunately, there's often no avoiding the mathematics behind collision detection. However, anyone with so much as a secondary-school maths education will be able to follow the collision detection explanations in this article.
Bounding sphere/circle test
The simplest of all methods for detecting intersections between objects is a simple bounding sphere test. Essentially, this represents objects in the world as circles or spheres, and test whether they touch, intersect or completely contain each other. This method is ideal when accuracy is not paramount, for objects roughly circular in shape, or in instances where these objects do a lot of rotations.
Each object will have a bounding circle defined by a centre point and a radius. To test for collision with another bounding circle, all that needs to be done is compare the distance between the two centre points with the sum of the two radii:
CircleCircleCollision Input Center1 x/y pair of floating points Centre of first circle R1 Floating point Radius of first circle Center2 x/y pair of floating points Centre of second circle R2 Floating point Radius of second circle Output True if circles collide Method // Calculate difference between centres distX = Center1.X – Center2.X distY = Center1.Y – Center2.Y // Get distance with Pythagoras dist = sqrt((distX * distX) + (distY * distY)) return dist <= (R1 + R2)
The above method can be optimized somewhat by comparing the square distance with the square of the sum of the radii instead, saving a comparatively slow square root operation, as shown below.
// Get distance with Pythagoras squaredist = (distX * distX) + (distY * distY) return squaredist <= (R1 + R2) * (R1 + R2)
|
Words from the readers
|
||||
|
It's all pseudocode, for ease of translating between languages.
Posted by Chippit at 16:53:33 on 20 May 2009
Which language is used in this tutorial?
Posted by Mozira at 16:41:09 on 20 May 2009
Have your say:
|
||||