Search code examples
javaopengl3dlwjgl

How to calculate a rectangular prism using min/max of X, Y, and Z vertices


I want to make a game where you are a player on a 3D plane, who is able to collide with objects around him. I plan to do collisions by wrapping all 3D models in the game with invisible rectangles that cannot be entered. I have written code to calculate the min/max of the X,Y, and Z of each vertex to find the highest and lowest point of each vertex. How would I make this into a rectangular prism?

Here is my code so far:

public CollisionModel(List<Vector3f> vert) {
    float xLow = 1000;
    float xHigh = 0;
    float yLow = 1000;
    float yHigh = 0;
    float zLow = 1000;
    float zHigh = 0;
    for(Vector3f v : vert) {
        if(v.x > xHigh) {
            xHigh = v.x;
        } else if(v.x < xLow) {
            xLow = v.x;
        }
        if(v.y > yHigh) {
            yHigh = v.y;
        } else if(v.y < yLow) {
            yLow = v.y;
        }
        if(v.z > zHigh) {
            zHigh = v.z;
        } else if(v.z < zLow) {
            zLow = v.z;
        }
    }
}

Solution

    1. the initial value of the min,max should be the first vertex not hard-coded 0,1000 !!!
    2. you find min,max that gives you bounding box which is what you called prism.

    Now you need to do collision testing. The problem is that your object can most likely move/rotate ... so you need apply transformations to your box first. So let construct the bounding box vertexes first. In 3D it is 8 points:

    p0 = ( xLow  , yLow , zLow  )
    p1 = ( xHigh , yLow , zLow  )
    p2 = ( xHigh , yHigh, zLow  )
    p3 = ( xLow  , yHigh, zLow  )
    p4 = ( xLow  , yLow , zHigh )
    p5 = ( xHigh , yLow , zHigh )
    p6 = ( xHigh , yHigh, zHigh )
    p7 = ( xLow  , yHigh, zHigh )
    

    Now apply object transformations to each of them. And lastly you need to add collision test. So you most likely want to test if 2 bounding boxes collide or not. For that you need test if any edge line of bbox1(q0..q7) intersects any face from bbox2(p0..p7). The faces are:

    p0,p1,p2,p3
    p4,p5,p6,p7
    p0,p1,p5,p4
    p1,p2,p6,p5
    p2,p3,p7,p6
    p3,p0,p4,p7
    

    and edge lines are:

    q0,q1
    q1,q2
    q2,q3
    q3,q0
    q4,q5
    q5,q6
    q6,q7
    q7,q4
    q0,q4
    q1,q5
    q2,q6
    q3,q7
    

    For the intersection itself you need to google the equation (I am too lazy to derive or search it for you) but here first google hit I found:

    Yes you can use triangle vs. line intersection as you face is 2 joined triangles ... There is also another option and that is convert the lines to coordinate system of the other bbox and then compute points for each line where one of the x,y,z = min and max and then just test if other two coordinates are in range or not ..