I got this half-working, (maybe somewhere to start from at least!) it works in the editor, but not in the game view, really it needs to do the world->screen calculation in the shader, not in update to cope with multiple cameras, but I haven’t got the parent-bounds-world-to-screen conversion working yet.
I attach this script to the children-to-be-clipped objects(blue) under the parent (green)
[ExecuteInEditMode]
public class ClippedChild : MonoBehaviour {
void Update () {
Camera cam = Camera.current;
if (!cam) {
return;
}
GameObject Parent = transform.parent.gameObject;
Vector4 ParentMin = cam.WorldToViewportPoint( Parent.renderer.bounds.min );
Vector4 ParentMax = cam.WorldToViewportPoint (Parent.renderer.bounds.max);
Material Mat = renderer.sharedMaterial;
Mat.SetVector("_ParentMin", ParentMin );
Mat.SetVector("_ParentMax", ParentMax );
}
}
Then this in a shader, also on the child object.
Shader "Custom/ClippedChild"
{
Properties {
_ColourInside ("ColourInside", Color) = (0,1,0,1)
_ColourOutside ("ColourOutside", Color) = (1,0,0,0.5)
_ParentMin("ParentMin", Vector ) = (0,0,0,0)
_ParentMax("ParentMax", Vector ) = (1,1,0,0)
}
SubShader {
Tags { "RenderType"="Transparent" }
LOD 200
CGPROGRAM
#pragma surface surf Lambert
float4 _ColourInside;
float4 _ColourOutside;
float4 _ParentMin;
float4 _ParentMax;
struct Input {
float3 worldPos;
float2 screenPos;
};
void surf (Input IN, inout SurfaceOutput o) {
float4 Colour = _ColourInside;
float2 ScreenPos = IN.screenPos;
float2 ScreenMin = _ParentMin.xy;
float2 ScreenMax = _ParentMax.xy;
if ( ScreenPos.x < ScreenMin.x || ScreenPos.x > ScreenMax.x ||
ScreenPos.y < ScreenMin.y || ScreenPos.y > ScreenMax.y
)
{
Colour = _ColourOutside;
//discard;
}
o.Albedo = Colour;
o.Alpha = Colour.a;
}
ENDCG
}
FallBack "Diffuse"
}
This code renders the pixel “in” or “out”, but you could use discard; to just not draw the pixel entirely, (colours just helped debug/demo)
As you can see, not wholly working yet, but I’ll see if I can get further. (I think just need to provide world-bounds positions to the shader and calculate the screen bounds there).
[25232-screen+shot+2014-04-15+at+3.57.06+pm.png|25232]