Home>
I have seen people ask questions about cutting objects before,If you are a beginner shader, it may not be very clear,Here is a relatively simple idea,Can be used directly if needed.(I haven't found a better method for cutting sutures)
Cutting principle:Directly discard the pixels in the world space whose y value (vertical cutting) is greater than the object's own coordinate y value within a certain range.
c#part:
using system.collections;
using system.collections.generic;
using unityengine;
public class discardtest:monobehaviour {
private material m;
private void start ()
{
m=getcomponent<meshrenderer>(). material;
}
void update () {
m.setfloat ("_ yfactor", transform.position.y);
}
}
Shader part:
shader "unlit/3ddiscardtest"
{
properties
{
_maintex ("texture", 2d)="white" {}
//The range of cutting (depending on the size of the actual object,(Assignment via c#)
_discardfactor ("discardfactor", range (-0.51,0.55))=0.0
//The color of the incision light
_lightcolor ("lightcolor", color)=(1,1,1,1)
//Width of light
_lightwidth ("lightwidth", range (0.0,0.1))=0.05
}
subshader
{
tags {"rendertype"="opaque"}
//You can't see the inside of the object without culling the back
cull off
pass
{
cgprogram
#pragma vertex vert
#pragma fragment frag
#include "unitycg.cginc"
struct v2f
{
float2 uv:texcoord0;
float4 vertex:sv_position;
float3 worldpos:texcoord1;
};
sampler2d _maintex;
float _yfactor;
float _discardfactor;
float4 _lightcolor;
float _lightwidth;
v2f vert (appdata_base v)
{
v2f o;
o.vertex=unityobjecttoclippos (v.vertex);
o.worldpos=mul (unity_objecttoworld, v.vertex) .xyz;
o.uv=v.texcoord;
return o;
}
fixed4 frag (v2f i):sv_target
{
float factor=_yfactor-i.worldpos.y + _discardfactor;
//_yfactor-i.worldpos.y=0 when the pixel is the center of the object,Pixels larger than 0 are below,Less than 0 pixels above,_discardfactor is smaller, the factor is smaller, the less reserved below
if (factor<0)
{
discard;
}
float4 color=tex2d (_maintex, i.uv);
//The part of factor<0 has been cut,The remaining part is cut with a border to make a stroke
if (factor<_lightwidth)
{
return _lightcolor;
}
return color;
//Optimized the writing of the above if, equivalent, but it looks more around
//float lerpfactor=saturate (sign (_lightwidth -factor));
//return color * (1-lerpfactor) + lerpfactor * _lightcolor;
}
endcg
}
}
}
Related articles
Related questions
- Unity Shader realizes the fog of 2D games
- Unity Shader realizes the sketch effect
- Unity Shader implements sketch-style rendering
- Unity Shader achieves graphics drawing (blue sky, white clouds and sea)
- Unity shader realizes the effect of vertex animation wave
- Unity shader to achieve glass refraction effect
- Unity Shader achieves dynamic fog effect
- Unity Shader achieves glass material effect
- Unity Shader intersection algorithm realizes simple anti-energy shield