Rect based collision detection

Problems with Canvas, OpenGL, etc...

Rect based collision detection

Postby Macok » Sat Jun 25, 2011 12:11 am

I need to provide collision detection to my 2d racing game.
My solution is to connect every car object with Rect object and make function like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. class Car{
  2.    public Rect bounds=...;
  3.    public boolean collides(Car anotherCar){
  4.        return this.bounds.intersect( anotherCar.bounds );
  5.    }
  6. }
Parsed in 0.012 seconds, using GeSHi
The problem is that when a car is turning, I have to rotate it's Rect to match new car's position.
Unfortunately, in documentation I haven't found any class that could keep a rotated Rect and provide intersect funtion.
How could it be solved?

Thanks in advance!

PS. It's my first project and I don't want to use andengine yet.
Posts: 2
Joined: Thu Jun 09, 2011 12:18 am


Re: Rect based collision detection

Postby MichaelEGR » Sat Jun 25, 2011 1:25 am

Can you use circles for your bounding shape? Does it closely enough match your car? This way collisions are easy to check for by distance between center points is less than the sum of the 2 radii? The nice things about circles or spheres for 3D is that it is rotation agnostic and provides the 1st check for early rejection. AABB against AABB (axis aligned bounding box) is also a basic check too that is fast too, but circles may very be all you need or at least you should get that working first.

If anything you will want to do this check first then if necessary check for collisions between two OBBs (oriented bounding box).

The basic circle vs circle collision code code is below; you can cut out a square root calculation by checking the combined radius^2:

float combinedRadii = sourceObject.radius + targetObject.radius;
dX = sourceObject.x - targetObject.x;
dY = sourceObject.y - targetObject.y;
if (combinedRadii * combinedRadii > dX * dX + dY * dY)
<collision occurred>

Some great articles to roll your own including collision response. You'll have to translate the code to Java. ... r-dummies/ ... r-dummies/ ... ds-part-1/ ... ds-part-2/
Founder & Principal Architect; EGR Software LLC
User avatar
Senior Developer
Senior Developer
Posts: 147
Joined: Thu Jan 21, 2010 5:30 am
Location: San Francisco, CA


Return to Android 2D/3D Graphics - OpenGL Problems

Who is online

Users browsing this forum: No registered users and 7 guests