1

I'm creating a 2d game. There are a lot of objects(oval, triangle etc) created by Bitmap. I'm going to detect collisions. Now I can do it only with rectange like this:

int x, y;
...
if(x>=bmp.getX() && x<=bmp.getX()+bmp.getWidth()
    && y>=bmp.getY() && y<=bmp.getY()+bmp.getHeight()) {
   //Collision.
}   

But there is one problem: I don't know how to do it with another figure (oval, triangle, etc). Any ideas will be appreciated. Thank you.

Nolesh
  • 6,848
  • 12
  • 75
  • 112

4 Answers4

2

A simple solution is to use sub rectangles to calculate collisions. The sub rectangles wont be able to cover the entire object but they can cover most of it.

This image should illustrate what I mean, it uses several rectangles for collision detection of a aeroplane

enter image description here

Another option (though NOT recommended) is to use per pixel color collision, if a colored pixel in the triangle intercepts a colored of an oval then there is a collision. Be warned this is computationally expensive.

Baz
  • 36,440
  • 11
  • 68
  • 94
triggs
  • 5,890
  • 3
  • 32
  • 31
2

1) for most figures try formula for intersection of edges to find more try ie:
How do you detect where two line segments intersect?
2) for intersection of circle and not circle, try distance from centre of circle to edge
How to tell if a line segment intersects with a circle?
3) intersection of two circles is easiest, just check is distance between both centres are lower than sum of their radius

Community
  • 1
  • 1
user902383
  • 8,420
  • 8
  • 43
  • 63
0

For oval you can use: -

if((Math.pow(x, 2) / Math.pow(a, 2)) + (Math.pow(y, 2) / Math.pow(b, 2)) < 1) {
     /** Point (x, y) is inside Oval **/
}

For Triangle, it is a little trivial task: -

Visit this link

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Thanks. But what about complicated objects like car or airplane? – Nolesh Oct 01 '12 at 10:40
  • 2
    Do you really want to use `^` (which is XOR)? Since this is a Java question, please change it to `Math.pow(x, 2)` or leave a note. – Baz Oct 01 '12 at 10:41
0

I faced the same problem as you, however with irregular Shapes. How I fixes the problem:

Create a Shape class that contains a list of Rectangles.

When first creating your game object, you should add Rectangles to the list so that a Shape is formed.

Now for collision detection; instead of just checking the one rect, iterate over all the rects in the list.

I hope this helps.

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73