Search code examples
java3dcollision-detectioncollision

Bounding Sphere Collision Does Not Work


I tried to implement collision between models in my LWJGL game and it seems that the objects are in constant collision, even when the collision radius is just 0.I have put the code for the collision below, as well as a link to a source that I was using to help with the bounding sphere collision.

package model;

import org.lwjgl.util.vector.Vector3f;

public class BoundingSphere {

    private Vector3f mid = new Vector3f();
    private float radius;

    public BoundingSphere(Vector3f midpoint, float radius) {
         this.mid = midpoint;
         this.radius = radius;
    }

    public boolean isColliding(BoundingSphere other){
        float diffX = (other.mid.x - mid.x);
        float diffY = (other.mid.y - mid.y);
        float diffZ = (other.mid.z - mid.z);

        float diffXSquared = (float) Math.pow(diffX, 2);
        float diffYSquared = (float) Math.pow(diffY, 2);
        float diffZSquared = (float) Math.pow(diffZ, 2);

        float radiusSums = (other.radius + radius);
        float radiusSumsSquared = (float)Math.pow(radiusSums, 2);

        if (diffXSquared + diffYSquared + diffZSquared > radiusSumsSquared){
            return true;
        }
        else{
            return false;
        }

    }

}

Collision Detection Page


Solution

  • It appears that you have inverted the condition. It is colliding only if:

    ((x2 + y2 + z2) <= r2)
    

    If you want overlap instead of collision then "<=" will be "<"