Cilenco
Cilenco

Reputation: 7117

OpenGL BoundingBox collision detection

For every object in my OpenGL scene I want to add a BoundingBox so I can use them for a simple collision detection. For this I created a simple BoundingBox class like this:

public class BoundingBox
{
    private float[] mathVector;

    public float[] minVector;
    public float[] maxVector;

    public BoundingBox(float minX, float maxX, float minY, float maxY,float minZ, float maxZ)
    {
        mathVector = new float[] {0, 0, 0, 0};

        minVector = new float[] {minX, minY, minZ, 1};
        maxVector = new float[] {maxX, maxY, maxZ, 1};
    }

    public void recalculate(float[] modelMatrix)
    {
        Matrix.multiplyMV(mathVector, 0, modelMatrix, 0, minVector, 0);
        System.arraycopy(mathVector, 0, minVector, 0, minVector.length);

        Matrix.multiplyMV(mathVector, 0, modelMatrix, 0, maxVector, 0);
        System.arraycopy(mathVector, 0, maxVector, 0, maxVector.length);
    }

    public boolean overlap(BoundingBox bb)
    {
        return (maxVector[0] >= bb.minVector[0] && bb.maxVector[0] >= minVector[0]) && 
               (maxVector[1] >= bb.minVector[1] && bb.maxVector[1] >= minVector[1]) && 
               (maxVector[2] >= bb.minVector[2] && bb.maxVector[2] >= minVector[2]);
    }
}

My problem now is that the recalculate function does not really work. I thought it is enought to multiply the matrix (because there the roatation, position and sclae is stored) with the vector it looks like it is not enought. What do I else have to do to get the recalculation work?

Upvotes: 1

Views: 995

Answers (2)

concept3d
concept3d

Reputation: 2278

You are using an axially aligned bounding box for a potentially rotated mesh. Since the box is axially aligned it can't deal directly with rotations. Yet, you can deal with this problem in multiple ways:

  • Use an oriented bounding box, this can be rotated so it can tracked the movement of your object one to one.
  • A more expensive way is to use an axially aligned box and recalculate the min and max, by transforming the vertices of the object and extracting the min and max each time the object is rotated, not only this is more expensive, the collision detection will usually be less accurate as an oriented bounding box will be less fit (depends on the shape of the object).

Upvotes: 3

Joe
Joe

Reputation: 301

I do something similar in my games. After transforming each of the 8 points on your min max box, you need to re-scan to find the new min max along each axis.

Think about the min max as a shoe box. The new matrix spins and stretchs it. After the transform, any of the 8 points could be the new min or max on any of the axes.

Upvotes: 3

Related Questions