Game Development of .Nettrix: GDI+ and Collision Detection - Extending the Algorithms to Add a Third Dimension
(Page 7 of 22 )
There are many advanced algorithms for 3-D collisions described on game-related sites all over the Internet. We’ll not stress the many implications on including a z axis in the collision detection algorithms; instead you just add some simple extensions to the preceding algorithms. This code sample depicts a proximity test with cube-like objects:
float Dx = Math.Abs(r2.x - r1.x);
float Dy = Math.Abs(r2.y - r1.y);
float Dz = Math.Abs(r2.z - r1.z);
…
if (Dx > (r1.extentX+r2.extentX) && (Dy > (r1.extentY+r2.extentY) && (Dz > r1.extentZ+r2.extentZ))
// The boxes do not overlap.
else
// The boxes overlap.
The next proximity algorithm extends the circle proximity test to use spheres in a 3-D space.
Dx = Math.Abs(Object1.CenterX - Object2.CenterX);
Dy = Math.Abs(Object1.CenterY - Object2.CenterY);
Dz = Math.Abs(Object1.CenterZ - Object2.CenterZ);
double Distance = Math.Sqrt(Dx*Dx + Dy*Dy + Dz*Dz);
if (Distance > Object1.radius+ Object2.radius)
// => The circles do not overlap.
else
// => The circles are overlapping.
The last proximity test is used for Sphere/Cube intersections. You probably already get the idea on how to extend these simple intersection tests. In the case of Arvo’s Algorithm, you simply add a test for the z axis.
…
// Check z axis. If Circle is outside box limits, add to distance.
if (CircleCenterZ < this.MinZ)
dist += Math.Sqr(CircleCenterZ – this.MinZ);
else if (CircleCenterZ > this.MaxZ)
dist += Math.Sqr(CircleCenterZ – this.MaxZ);
// Now that distances along x, y, and z axis are added, check if the square
// of the Circle's radius is longer and return the boolean
result. return (Radius*Radius) < dist;
return (Radius*Radius) < dist;
In the next sections you’ll see how to apply these theoretical ideas in a real game project.
This chapter is from Beginning .NET Game Programming in C#, by David Weller, et al., (Apress, 2004, ISBN: 1590593197). Check it out at your favorite bookstore today.
Buy this book now. |
Next: Develop a Real Game Proposal >>
More .NET Articles
More By Apress Publishing