"Synchronize" Backface Culling

I got a quad primitive which some objects in front of it. The quad represents some kind of wall. I want the wall to be visible from one side only, back face culling comes in handy here. :wink:
However, as soon as the quad is backface culled, the objects infront of the quad should disappear.
So I’d need something like (Pseudocode):

objects.visible = !wall.backfaceCulled

I got it working for orthographic projection by going through a manual culling process:

  • I calculate the normal of the triangle of the quad
  • I use the dot product of that normal with the camera direction and check whether its > 0.
  • If < 0, the renderer ob the objects in front of the wall are disabled.

It works fine with orthographic projection, however I’m missing something regarding perspective:
The normal of the quad would need to be “distorted” by the projection view as in the following picture:

Yellow shows the calculated normal. If it would follow the blue line, the culling should work fine.

            // filter is the MeshFilter of my quad     
            var v0 = filter.mesh.vertices[0];
            var v1 = filter.mesh.vertices[1];
            var v2 = filter.mesh.vertices[3];

            // Local space to world space
            var v0World = visibilityParent.transform.TransformPoint(v0);
            var v1World = visibilityParent.transform.TransformPoint(v1);
            var v2World = visibilityParent.transform.TransformPoint(v2);

            // Calc normal
            var sideVec1 = v1World - v0World;
            var sideVec2 = v2World - v0World;
            var normal = Vector3.Cross(sideVec1, sideVec2);
            normal.Normalize();

            var visible = Vector3.Dot(normal, Camera.main.transform.forward) > 0;

Any ideas?
Thank you in advance.

There’s not really a need to calculate the normal. Assuming you’re using the default quad you can just use transform.forward to get the normal direction (actually going to be -transform.forward). Then for the dot product you want use the world space relative vector from the camera to the quad’s transform rather than camera forward, assuming you’re using a perspective camera and not orthographic.

var visible = Vector3.Dot(-transform.forward, transform.position - Camera.main.transform.position) > 0.0f;

That might be backwards.

Thank you really much, it works.
I really overcomplicated this. :slight_smile: