Reputation: 558
I'm writing a 2D platformer in Java, and I've run into a problem. I have two objects: Both have bounding boxes, and four coordinates to represent the corners of the boxes.
My issue is that I am trying to find a way to simulate collision, but I just can't seem to do it. I've tried searching all over the place, but most sites just demonstrate OpenGL tactics.
Let us represent the bounding box coordinates like so:
TL: Top-left
TR: Top-right
BL: Bottom-left
BR: Bottom-right
Here is how I originally proposed testing collision:
if(TL1 > TL2 && TL1 < TR2) //X-axis
//Collision happened, TL1 corner is inside of second object
else if(BL1 < TL2 && BL1 > BL2) //Y-axis
//Collision happened, BL1 corner is inside of second object
This is a very crude way of showing it, but basically I'm checking to see if a corner intersects the other object. The problem is, it doesn't account for both axii. That is to say, an x-collision will occur even if one object is above the other.
If I check for collision on both axii, then there is no way of telling whether it was a horizontal or vertical collision. Or maybe there is and I haven't figured it out.
Can anyone point me in the right direction?
Upvotes: 0
Views: 1558
Reputation: 8254
this is from java.awt.Rectangle.
you should be able to modify it to suit the coords you have.
/**
* Determines whether or not this <code>Rectangle</code> and the specified
* <code>Rectangle</code> intersect. Two rectangles intersect if
* their intersection is nonempty.
*
* @param r the specified <code>Rectangle</code>
* @return <code>true</code> if the specified <code>Rectangle</code>
* and this <code>Rectangle</code> intersect;
* <code>false</code> otherwise.
*/
public boolean intersects(Rectangle r) {
int tw = this.width;
int th = this.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = this.x;
int ty = this.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) &&
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry));
}
Upvotes: 1