## Rect based collision detection

Problems with Canvas, OpenGL, etc...

### Rect based collision detection

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:
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 1.0.8.4
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?

PS. It's my first project and I don't want to use andengine yet.
Macok
Freshman

Posts: 2
Joined: Thu Jun 09, 2011 12:18 am

### Re: Rect based collision detection

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:

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.

http://www.wildbunny.co.uk/blog/2011/04 ... r-dummies/
http://www.wildbunny.co.uk/blog/2011/04 ... r-dummies/
http://www.wildbunny.co.uk/blog/2011/05 ... ds-part-1/
http://www.wildbunny.co.uk/blog/2011/06 ... ds-part-2/
Founder & Principal Architect; EGR Software LLC
http://www.typhonrt.org
http://www.egrsoftware.com

MichaelEGR
Senior Developer

Posts: 147
Joined: Thu Jan 21, 2010 5:30 am
Location: San Francisco, CA