Hi all
Has anyone had any succeess with shaders and only rendering what is inside a mesh (simply a box). I have been messing around with stencil shaders, but its not quite offering fully what i want as when the object is outside the box but the camera looks though the box you can still see the object. What i would be looking for is that this object to still not render (or the parts of the object that are out the box).
Thanks for any Help.
4 Answers
4
An arbitrary mesh might be difficult but if it’s just a box and you have no problem with using a special shader for the content of the box then it’s relatively simple:
Put this script on the box:
using UnityEngine;
[ExecuteAlways]
public class ClipBox : MonoBehaviour {
void Update() {
Shader.SetGlobalMatrix("_WorldToBox", transform.worldToLocalMatrix);
}
}
And this shader on everything else:
Shader "Custom/ClipBox" {
Properties {
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
#pragma surface surf Standard fullforwardshadows addshadow
#pragma target 3.0
sampler2D _MainTex;
half _Glossiness;
half _Metallic;
float4x4 _WorldToBox;
struct Input {
float2 uv_MainTex;
float3 worldPos;
};
void surf (Input IN, inout SurfaceOutputStandard o) {
float3 boxPosition = mul(_WorldToBox, float4(IN.worldPos, 1));
clip(boxPosition + 0.5);
clip(0.5 - boxPosition);
fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
o.Albedo = c.rgb;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
The magic happens in these three lines:
float3 boxPosition = mul(_WorldToBox, float4(IN.worldPos, 1));
clip(boxPosition + 0.5);
clip(0.5 - boxPosition);
We calculate the position of the fragment relative to the box, which then makes it easy to cut away any fragments outside of it.
how could you get this working with URP ?
How can i set the scale of box…?
I was trying to change all of attribute. But, Not change Box bound.
I mean Box is ClipBox…
Is there a way to turn the effect on and of in the inspector? I can only see the geometry that is inside of the clipping box, and that makes it a bit hard to work on the geometry? Or should I just wait until I’m done with the designing of the geometry until I apply the effect?
This is brilliant, thanks very much :)
– ReddevildraggReally glad your solution give the correct result, but i have a bit of the problem understand the magic number 0.5 here. I know the boxPosition is the position of each vertex relative to the box, i original thought 0.5 is some kind of distance value, so i try other but i found lower value give the wrong result. Also, i am trying the do the opposite, i want the object with shader invisible in box and only be visible outside of the box, i try to play around with the clip function in code with no luck, do you know how to do that? Thx in advance!
– Philoctetes