Getting the position of the top 4 corners of a boxcollider

Maybe someone could give me a hand. I’m currently trying to calculate/get the position of the top 4 corners/edges of a boxcollider.

Is there any easy way to do that?

You’ll probably want to get the size of the boxcollider, and then calculate those positions yourself. If you use transform.TranformPoint(size.x/2, size.y/2, size.z/2), for example, that should give you the front-top-right corner in worldspace. You can swap the signs on the X and the Z of those to get the other top corners (keep the Y positive).

1 Like

@StarManta is right, don’t forget scale though. Here’s some code, haven’t tested it, let me know if anything blows up…

To get ALL the corners, try:

Transform box; // This is the box
        BoxCollider boxCollider = box.GetComponent<BoxCollider>(); // This is the box's BoxCollider

        // Box Collider center in world coordinates
        Vector3 centerWorld = box.position + Vector3.Scale(box.localScale, boxCollider.center);
      
        // Box Collider world size
        Vector3 sizeWorld = Vector3.Dot (box.localScale, boxCollider.size);
      
        for (int i = -1; i <= 1; i+=2){
            for (int j = -1; j <= 1; j+=2){
                for (int k = -1; k <= 1; k+=2){
                    float xCoord = centerWorld.x + i*(sizeWorld.x/2);
                    float yCoord = centerWorld.y + j*(sizeWorld.y/2);
                    float zCoord = centerWorld.z + k*(sizeWorld.z/2);  
                    Vector3 anotherCorner = new Vector3(xCoord, yCoord, zCoord);
                    //Store it somewhere          
                }              
            }
        }

Now to just get the top corners, remove the middle for loop and set yCoord = sizeWorld.y/2;

transform.TransformPoint takes the transform scale into account.

@StarManta too true, I missed that. Overall your idea is much, much neater then. I keep getting caught out by people who know more about how to use Unity’s built in functions :wink:

Using transform.TranformPoint() I was putting in the scale of the object / 2 as the size but you just have to put in a constant. Like doing transform.TransformPoint(.5, .5, .5) will still have the same scale as the object. It also is effected by the rotation of the object.

What I’m trying to say is that it takes into count position, scale, and rotation haha.