Christian Vucossa programming blog

game programming, daily troubles and solutions

Posts Tagged ‘collision detection’

3D Pong collision detection: the simple way

Posted by Christian on December 12, 2008

As said in previous posts I’m actually working on a Pong clone in OpenGL, SDL and C++.

Topic of this post is Pong’s collision detection.

In a 2D environment this is quite easy and deserve of a very poor math, since we have a defined screen resolution, defined objects size and a perfect 1 to 1 relationship between units and pixels. We simple need of some x,y calculations.

But what in a 3D env? First, we don’t have relationship between pixels and units. Second, object can be translated and scaled, which means their size can change.

There are quite a few algorithms for 3D collision detection, I know of their existance but I master only one of them at the moment: Bounding Spheres.

Anyway, I tried with bounding spheres (which probably will be topic for another post) but I realize this is not the best suitable alg for the cause. In Pong we have to deal mostly with stretched cubes, and a sphere is not the best geometric figure to surround them. What we need is probably a Bounding Box version of the algorithm but… wait a moment.

Maybe what we really need is only a 3d adaption of our old, plain 2D algorithm.

Sure, we can’t tell how long or how fat is our racket or our ball, but we can calculate where object is on the 3D space, and with a little effort we can tell which vertex is the more up, the more right, the more left and the more bottom.

We can do that simply passing through all our object’s vertexes and locate the one with the higher y value, which will be the most up, then the one with the lowest y, the most bottom and so on with the x values.

At the end we have 4 vertexes for every object in the scene describing their borders.

But the ball is moving, and the rackets too. We need to keep update this borders with the object’s translations. But this is simple: if object translate up (0,1,0) we translate up all 4 border vertexes by the same values. Vertexes follow the object movements, of course.

And if the object scales? Well, we scale the borders too in the same way.

So, here we are with our vertexes. And now? Eheh, now the easy part. Each loop we only have to  check ball borders with rackets and field opposite borders in order to detect collisions.

For example: if ball’s right border is major or equal to player 2 racket’s left border (assuming player 2 is the one on the right) we have a collision.

if( ball.maxX() >= player2.minX() ){

ball.collideRight();

}

Easy, isn’t it?

Posted in game programming | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.