Reputation: 1297
I'm trying to accomplish collision detection. Im not using OpenGl, I'm using canvas/surfaceview.
I have 2 bitmaps. This is what ive come up to so far:
public boolean inBounds(int x2,int y2, int x,int y,int width,int height){
if(x2 > x && x2 < x + width -1 && y2 > y && y2 < y + height -1){
return true;
}
return false;
}
This does run but it only detects collision if x2 and y2's corner is inside the other object.
So how do I improve my collision detection?
This image I found on the web should detect collision in my program.
//Simon
Upvotes: 2
Views: 2862
Reputation: 177
The android.graphics.Rect class contains some nice functions to do this in one line. You can check out intersect.
Upvotes: 0
Reputation: 5045
bool isIntersect(Rectangle a, Rectangle b){
return a.Left < b.Right && a.Top < b.Bottom &&
b.Left < a.Right && b.Top < a.Bottom;
}
bool isIntersect(Circle a, Circle b)
{
Vector<ClassWithLengthRadiusProp> vDistanceProp = a.Center - b.Center;
return vDistanceProp.Length < a.Radius + b.Radius;
}
bool isIntersect(Circle a, Circle b)
{
Vector<ClassWithLengthRadiusProp> vDistanceProp = a.Center - b.Center;
float radiusSum = a.Radius + b.Radius;
float squaredDistanceLength = vDistanceProp .x * vDistanceProp .x +
vDistanceProp .y * vDistanceProp .y;
return squaredDistanceLength < radiusSum * radiusSum;
}
Upvotes: 1
Reputation: 1532
If they are circles then here's a little pseudo code for you:
if (Math.sqrt(Math.pow(bitmap1.centerX-bitmap2.centerX, 2) + Math.pow(bitmap1.centerY-bitmap2.centerY, 2))<=bitmap1.width)
return true;
else
return false;
Since you now want rectangles (and assuming they're different sizes):
if (Math.abs(bitmap1.centerX-bitmap2.centerX)<=(bitmap1.width+bitmap2.width)/2f
&& Math.abs(bitmap1.centerY-bitmap2.centerY)<=(bitmap1.height+bitmap2.height)/2f)
return true;
else
return false;
Hope that helps!
Upvotes: 2
Reputation: 1766
if(r1.lowerLeft.x < r2.lowerLeft.x + r2.width
&& r1.lowerLeft.x + r1.width > r2.lowerLeft.x
&& r1.lowerLeft.y < r2.lowerLeft.y + r2.height
&& r1.lowerLeft.y + r1.height > r2.lowerLeft.y)
return true;
else
return false;
That should do it unless you want to do a circle collision detection. r1 & r2 and defined as Rects
Upvotes: 0