Reputation: 89
I already know about rectangle collision detection with rectangles, but this time I have 2 rotated bitmaps. I mean, I have normal bitmaps + a float variable called "direction" and telling in which direction the bitmap must be rotated at drawing.
But how do I find out if 2 of those objects are bumping into each other? It would be enought, too, if you could say me how collision detection between 2 rotated rectangles works... Or maybe you could post some code...
Thank you if you can help (and thank you if you spent time on reading this or thinking about an answer)
Upvotes: 1
Views: 1850
Reputation: 3321
Generally, you will needto use the Separating Axis Theorem to determine whether two rotated rectangles are colliding. But there is a simple way that you can tell whether the rectangles are colliding prior to using the SAT so that you don't have to do unneccesary processing. You can do a bounding circle check, where you prove that the rectangles dont intersect by proving that their bounding circles dont intersect.
The bounding circle of a rectangle shares its center and has a diameter equal to the length of either diagonal of the rectangle. Essentially, if the circles do not intersect, than the rectangles cannot intersect either.
I'm not sure how you are performing your rotations, but if you are using Shape/Area type objects, you can use AffineTransform
to perform the rotation and then use intersects()
on the Area of each rotated object to check if they collide, this saves you from implementing it yourself. Consider the following example:
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
public class Main {
public static void main(String args[]) {
//Create rectangle
Rectangle rect = new Rectangle(10, 10, 10, 10);
//Create transformation object
AffineTransform af = new AffineTransform();
//Rotate the rectangle by 45 degrees
af.rotate(Math.PI/4, rect.x, rect.y);
Rectangle rect2 = new Rectangle(20, 20, 20, 20);
AffineTransform bf = new AffineTransform();
bf.rotate(Math.PI/4, rect2.x, rect2.y);
//Create Area objects based off of the Rectangle objects
Area areaA = new Area(rect);
//Set the Area object to be the same as the Rectangle object
areaA = areaA.createTransformedArea(af);
Area areaB = new Area(rect2);
areaB = areaB.createTransformedArea(bf);
//Check if the objects collide by using their Area equivalent
if (areaA.intersects(areaB.getBounds())) {
System.out.println("Collision!");
}
}
}
You can obviously, modify this to suite your implementation - I'm hoping this points you in the right direction.
Upvotes: 1