So I have a triangular face mesh (just 3 vertices, as shown in the screenshot below - green triange) which I am using to create a plane (mathematical plane, not a plane mesh). I am then converting this plane into a Vector4
(normal.x, normal.y, normal.z, distance) and using this to create an oblique clipping plane with Camera.CalculateObliqueMatrix().
Here is what my scene looks like
What I want is for everything behind the clipping plane (green triangle) to be rendered and everything in front to be clipped as show below (green tint = render, red tint = clip)
And here is a gif that shows what happens when I press play and rotate the camera.
(Link if it isn’t showing for you)
As you can see the issue I am having is that this also introduces some kind of far-clipping plane which is clipping where I don’t want to and also the direction of clipping (each side of plane) changes as I rotate the camera which I don’t want.
Any help would be greatly appreciated
Here is the full code
using UnityEngine;
public class ObliquePlaneTest : MonoBehaviour {
private Vector4 clipPlane;
private Plane plane;
public GameObject planeGO;
private Vector3[] vertices;
private Mesh planeMesh;
// Use this for initialization
void Start () {
planeMesh = planeGO.GetComponent<MeshFilter>().mesh;
}
// Update is called once per frame
void Update () {
vertices = planeMesh.vertices;
for (int i = 0; i < 3; i++)
{
vertices[i] = planeGO.transform.TransformPoint(vertices[i]);
}
plane = new Plane(vertices[0], vertices[1], vertices[2]);
//This just draws a ray from the plane (closest) point to the camera (same as normal vector)
Debug.DrawRay(Camera.main.transform.position - plane.normal * plane.GetDistanceToPoint(Camera.main.transform.position), plane.normal * plane.GetDistanceToPoint(Camera.main.transform.position), Color.red);
Vector4 clipPlaneWorldSpace = new Vector4(plane.normal.x, plane.normal.y, plane.normal.z, -Vector3.Dot(plane.normal, planeGO.transform.position));
Vector4 clipPlaneCameraSpace = Vector4 clipPlaneCameraSpace = Matrix4x4.Transpose(Camera.main.cameraToWorldMatrix) * clipPlaneWorldSpace;
Camera.main.projectionMatrix = Camera.main.CalculateObliqueMatrix(clipPlaneCameraSpace);
}
}
If it helps, here are some of my references I’ve been using
Source code, github
Source code, unity forums
A short paper on the subject, terathon
Plane, unity docs
CalculateObliqueMatrix, unity docs