collision detection for squares

Hi, I need help to implement collision detection:

I’ve 2 squares with (x1,y1) and (x2,y2) coordinates.

What kind of control I’ve to do??

Have a look at the API:
class: Rectangle.
method: intersects(…).

This should do the job.

Regards

Ralf

I can’t use the class Rectangle… but where I can look the implementation of intersects?

Download the Java SDK, or JDK or whatever they’re calling it now. It’ll include the source code and then you can look at the Rectangle class and see how they’ve written the intersects() method.

I think that when one is doing collision-detection, one should be able to figure how to do this…


if(
   1 of 4 corners of rect A is inside area of B
   ||
   1 of 4 corners of rect B is inside area of A
  )
{
   // collision
}

With a dozen ways to optimize the above :slight_smile:

Check for non-intersection on each axis. eg for the x asis;

if(s1.x+s1.w < s2.x || s1.x > s2.x+s2.width)
return false;

works for me anyway.

Here is something I hacked up this morning around 4am.
It works really well. :slight_smile:


public boolean hasCollided(Entity entity, Entity entity2) {
		boolean collisionOccured = false;
		
		tmpPoint.setLocation(entity.getX(), entity.getY());
		collisionOccured = isInside(tmpPoint, entity2);
		
		tmpPoint.setLocation(entity.getX() + entity.getWidth(), entity.getY());
		collisionOccured |= isInside(tmpPoint, entity2);
		
		tmpPoint.setLocation(entity.getX() + entity.getWidth(), entity.getY() + entity.getHeight());
		collisionOccured |= isInside(tmpPoint, entity2);
		
		tmpPoint.setLocation(entity.getX(), entity.getY() + entity.getHeight());
		collisionOccured |= isInside(tmpPoint, entity2);
	
		if(collisionOccured)
			vecPoint.setLocation(entity2.getX() - entity.getX(), entity2.getY() - entity.getY());
		
		return collisionOccured;
	}
	
	public boolean isInside(Point point, Entity entity) {
		boolean isInside = false;
		
		isInside = (point.x >= entity.getX()) && (point.x <= (entity.getX() + entity.getWidth()));
		isInside &= (point.y >= entity.getY()) && (point.y <= (entity.getY() + entity.getHeight()));
		
		return isInside;
	}

If you only check for wether any vertices interesect the other rect you will miss some situations. Also do you have to use point object instead of primitives!

Uhm… no. Say both rects overlap in the middle like some cross. None of the corners would be inside but they would still collide.

I’ve tested extensively and haven’t found that to be the case.
Objects aren’t being created everytime they are passed, so to keep things clean I use points.