Please imagine a scene that shows a cube. Both the camera and the cube can be randomly positioned and rotated. How can you tell which side of the cube is facing up/down or left/right?

Or in other words: What's the math to find a cube's orientation in relation of the camera?

Your advise is very much appreciated. Thank you.

Edit: Here's a screenshot:

enter image description here

The camera is "locked" onto the cube. I.e. one of it's sides is facing directly into the camera. Both cube and camera are rotated in 90 degree steps, so that each face of the cube is always in parallel to the camera's axis's. How can you tell which face (or color in the screenshot above) is pointing left/right/up/down?

Thank you!


1 Answer 1


First let's label each cube face.

I'll do this in a specific order, with the negative axes first, then the positives. ±z are on the outside edges of the list, and ±x are on the inside. I'll leave a default/unassigned value in the middle of the range.

public enum CubeFace: sbyte {
    Back   = -3,  // -z
    Bottom = -2,  // -y
    Left   = -1,  // -x
    None   =  0,
    Right  =  1,  // +x
    Top    =  2,  // +y
    Front  =  3   // +z

Now, since you've locked your camera/cube to 90-degree rotations, once we transform the camera's direction into the cube's orientation, we know it has to be (±1, 0, 0) or (0, ±1, 0) or (0, 0, ±1), (or within a small rounding error of these six values). By multiplying x, y, and z by 1, 2, and 3 respectively, we get the corresponding enum value.

public CubeFace FaceInDirection(transform cube, Vector3 worldDirection) {
    var local = cube.InverseTransformDirection(worldDirection);

    int code = Mathf.RoundToInt(local.x + 2 * local.y + 3 * local.z);

    return (CubeFace)code;

Now you can get the face in a particular camera direction like so...

var rightFace  = FaceInDirection(cubeTransform,  cameraTransform.right);

var topFace    = FaceInDirection(cubeTransform,  cameraTransform.up);

var facingFace = FaceInDirection(cubeTransform, -cameraTransform.forward);



You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .