Does the camera transform in Unity invert directions at the end?

26 views Asked by At

I want the 8 corners of the camera frustum and I have this:

    Vector3 nearTopLeft = center_near + (up * (height_near / 2)) - (right * (width_near / 2));
    Vector3 nearTopRight = center_near + (up * (height_near / 2)) + (right * (width_near / 2));
    Vector3 nearBottomLeft = center_near - (up * (height_near / 2)) - (right * (width_near / 2));
    Vector3 nearBottomRight = center_near - (up * (height_near / 2)) + (right * (width_near /2));

    Vector3 farTopLeft = center_far + (up * (height_far / 2)) - (right * (width_far / 2));
    Vector3 farTopRight = center_far + (up * (height_far / 2)) + (right * (width_far / 2));
    Vector3 farBottomLeft = center_far - (up * (height_far / 2)) - (right * (width_far / 2));
    Vector3 farBottomRight = center_far - (up * (height_far / 2)) + (right * (width_far / 2));

However, only the near plane positions are correct: up and right are the camera.transform (.right and .up, respectively), but the far plane positions are inverted: for some reason the top positions show below, and the bottom positions show above (and the same with left and right: the swap). I could just alter the values since I know this and it would work, but I want to understand why is this happening.

I tried debugging the values of right, up and forward (camera.transform.right = (1, 0, 0); up (0, 1, 0) and forward (0, 0, 1)) expecting them to be weird, but they weren't. As I said earlier, I really don't have to try something since I know how to solve it (just swap the numbers to the weird correct values), but again, I want to understand it. (And either the internet isn't helping or am just too terrible doing research).

1

There are 1 answers

0
derHugo On

Simply use Camera.CalculateFrustumCorners e.g.

var nearCorners = new Vector3[4];
camera.CalculateFrustumCorners(new Rect(0, 0, 1, 1), camera.nearClipPlane, Camera.MonoOrStereoscopicEye.Mono, nearCorners);

var farCorners = new Vector3[4];
camera.CalculateFrustumCorners(new Rect(0, 0, 1, 1), camera.farClipPlane, Camera.MonoOrStereoscopicEye.Mono, farCorners);

for(var i = 0; i < 4; i++)
{
    nearCorners[i] = camera.transform.TransformVector(nearCorners[i]);
    farCorners[i] = camera.transform.TransformVector(farCorners[i]);
}