atoms118
atoms118

Reputation: 105

Java - Shape Collision Detection

OK, so I know that this question has already been asked a million times, but I have a slightly different problem. I have Polygon objects, which are made from 1 unit "blocks", and I need to determine if the blocks touch each other. Other answers have had code like this:

Area area1 = new Area(poly1);
Area area2 = new Area(poly2);
area1.instersect(poly2);
if(!area1.isEmpty()) {

    // Do collision stuff here

}

This has a problem though, which is that if the shapes are next to each other (they are touching), this would not report a collision.

My original idea was to have one Polygon have a 1 unit border around it, so if they were next to each other, the border would intersect with the second Polygon and I would get a collision. I can't seem to find a way to add a border though.

Help is greatly appreciated!

EDIT:

If this matters, all blocks are 1x1 unit in size, and are stored in "chunks" (With an ArrayList). My Polygon objects represent a whole chunk of objects. If there is a better way to do this, please let me know!

My code needs to be as efficent as possible, as I potentially have hundreds of chunks/thousands of blocks, and the physics loop runs every 1 second

Upvotes: 2

Views: 688

Answers (2)

atoms118
atoms118

Reputation: 105

Alright, I think I have a solution, please comment if I've got this right.

I'll use the ArrayList of blocks to create 3 unit wide rectangles per block (With x - 1) instead of 1 unit blocks, which should give me a 1 unit border around the Area object:

public Area calculateHitboxArea() {
    Area area = new Area();
    for(int i = 0; i < getMass(); i++) {
        Block block = getBlock(i);
        area.add(new Area(new Rectangle(block.getX() - 1, block.getY() - 1, 3, 3)));
    }
    return area;
}

I also keep my original method for finding the Area of a chunk, and I can then check collisions with this:

Area area1 = chunk1.calculateHitboxArea();
Area area2 = chunk2.calculateArea();
area1.intersect(area2);
if(!area1.isEmpty()) {

    // Collision stuff here

}

Do increase performance, my chunk class will cache the area both methods return, so the Area objects will only be generated when the physics loop modifies the chunks.

Not sure if this is really the best way to do this, as it means in my case that I will need 4 Area objects in memory per chunk, which is not ideal. I'm not going to mark this answer ass accepted unless it gets many upvotes, as I'd still prefer a more efficient way to do this.

Upvotes: 1

Akash
Akash

Reputation: 593

public static boolean checkCollision(Shape shapeA, Shape shapeB) {
   Area areaA = new Area(shapeA);
   areaA.intersect(new Area(shapeB));
   return !areaA.isEmpty();
}

Upvotes: 0

Related Questions