Why is my implementation of SAP returning false positives

by The Masked Rebel   Last Updated May 16, 2018 12:13 PM

I am trying out collision detection in my game and came up with this code for sweep and prune:

    if(objects.isEmpty()) return;
    for(int i = 1;i < objects.size();i++) {
        for(int j = 0; j<objects.size();j++) {
            if(objects.get(i).getMin()[0] > objects.get(j).getMin()[0])
            {

                Entity entity = objects.get(i);
                Entity entity1 = objects.get(j);
                float temp = objects.get(i).getMin()[0];
                entity.getMin()[0] = objects.get(j).getMin()[0];
                entity1.getMin()[0] = temp;
               if(!(entity.isStaticObject() && entity1.isStaticObject())) {
                   System.out.println(entity.getName() + " : " + entity1.getName());
                        if(checkFullCollision(entity, entity1)) {
                                addOverlappingPair(entity,entity1);
                            }
                    }
            }
         }
    }

When it didn't work,I debugged the code and found that the code above was working but the bottom bit where I check my collisions was not working.

Here is all the code related to the bottom part.

if(checkFullCollision(entity, entity1)) {
                            addOverlappingPair(entity,entity1);
                        }

Where i check my collisions

    private static boolean checkFullCollision(Entity entity, Entity entity1) {
    float[] amin = entity.getMin();
    float[] amax = entity.getMax();


    float[] bmin = entity1.getMin();
    float[] bmax = entity1.getMax();
    return  (amin[0] <= bmax[0] && amax[0] >= bmin[0]) &&
            (amin[1] <= bmax[1] && amax[1] >= bmin[1]) &&
            (amin[2] <= bmax[2] && amax[2] >= bmin[2]);
}

where I calculate my min and max.

    public float[] getMax() {
    final float[] max = new float[3];
    max[0] = position.x + this.max.x;
    max[1] = position.y + this.max.y;
    max[2] = position.z + this.max.z;
    //System.out.println(position);
    return max;
}

public float[] getMin() {
    final float[] min = new float[3];
    min[0] = position.x - this.min.x;
    min[1] = position.y - this.min.y;
    min[2] = position.z - this.min.z;
    return min;
}

    private static Vector3f getExtreme(final List<Vertex> vertices,
        final BinaryOperator<Float> op) {
    final float x = vertices.stream().map(v -> v.getPosition().x).reduce(op).orElse(0f);
    final float y = vertices.stream().map(v -> v.getPosition().y).reduce(op).orElse(0f);
    final float z = vertices.stream().map(v -> v.getPosition().z).reduce(op).orElse(0f);
    return new Vector3f(x, y, z);
}

Vector3f min = getExtreme(vertices, Math::min);
    Vector3f max = getExtreme(vertices, Math::max);


Related Questions


LibGDX Bounding Rectangles

Updated April 19, 2015 20:05 PM

Java 3D collision detection with JBullet

Updated May 27, 2017 20:13 PM