Search Unity

Oblique Projection Matrix offsetting when camera rotates around X axis

Discussion in 'Scripting' started by Prodigga, Jul 7, 2015.

  1. Prodigga

    Prodigga

    Joined:
    Apr 13, 2011
    Posts:
    1,123
    Hey guys

    I've managed to apply an oblique projection matrix to my game camera and have it clip everything behind a plane. I will be using this for a mirror effect.

    Everything works fine except when I rotate the camera around X. I have hard coded the clipping plane - Vector3.zero is a point on the plane and Vector3.forward is the planes normal. Here is what it looks like - you can see me rotate around the Y axis just fine, but when I try to rotate around the X axis the clipping plane moves forwards and backwards.

    Here is my script. I think maybe something is wrong with the way I calculate the the camera space plane?



    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Reflection;
    4.  
    5. public class ClipTest : MonoBehaviour
    6. {
    7.     void Update()
    8.     {
    9.         Camera.main.ResetProjectionMatrix ();
    10.  
    11.         Matrix4x4 obliqueProjection  = Camera.main.projectionMatrix;
    12.  
    13.         Vector4 cameraSpaceClipPlane = CameraSpacePlane(Camera.main, Vector3.zero, Vector3.forward, 1.0f,0);
    14.        
    15.         Camera.main.projectionMatrix = Camera.main.CalculateObliqueMatrix(cameraSpaceClipPlane);
    16.     }
    17.  
    18.     static Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign, float val)
    19.     {
    20.         Vector3 offsetPos = pos + normal * val;
    21.         Matrix4x4 m = cam.worldToCameraMatrix;
    22.         Vector3 cpos = m.MultiplyPoint(offsetPos);
    23.         Vector3 point = m.inverse.MultiplyPoint(new Vector3(0.0f, 0.0f, 0.0f));
    24.         cpos -= new Vector3(0.0f, point.y, 0.0f);
    25.         Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
    26.         return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal));
    27.     }  
    28. }
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    You've clearly copied this from http://forum.unity3d.com/threads/oblique-near-plane-clipping.194722/ (or whever he copied from) but you've changed 'val' from 0.07 into 0, which means that offsetPos is just pos, buceause you multiply normal by zero
    Plus I don't really get the whole CameraSpacePlane function, CalculateObliqueMatrix just needs a plane, which in your case is (0,0,1,0) (unless it's in camera space, the docs isn't clear on that)

    regardless, I've never bothered with this function, When I've played with camera frustums, I've used my own thing, which has been posted here:
    http://forum.unity3d.com/threads/us...reate-holographic-effect.291123/#post-1949423
    (and other threads)