这个函数颇费我的脑力,都怪国内的博客写的跟屎样,都是抄写,没有一个自己的原创和感悟,下面我来讲下这个函数的真正意义。
参考:UnityUI.cginc中的函数:
inline float UnityGet2DClipping (in float2 position, in float4 clipRect)
{
float2 inside = step(clipRect.xy, position.xy) * step(position.xy, clipRect.zw);
return inside.x * inside.y;
}
其函数的真正意义是判断一个点是否在矩形区域内,如果是返回的是1,否则返回0。
这个还是在日文网上找到的解析:
指定の矩形範囲(clipRect)の中なら1.0を、その範囲外なら0.0を返す関数です。
それがアルファに乗算してあります。
参考网址:http://logicalbeat.jp/blog/575/
这个可以百度翻译就行了。
然后我们的例子如下:
一个quad就可以说明这个问题了。
shader代码如下:
Shader "MyShader/Clip"
{
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "UnityUI.cginc"
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
float4 vertex : SV_POSITION;
float4 worldPosition : TEXCOORD1;
};
float4 _ClipRect;
v2f vert(appdata v)
{
v2f o;
o.worldPosition = mul(unity_ObjectToWorld, v.vertex);
o.vertex = UnityObjectToClipPos(o.worldPosition);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed4 col;
float xx = UnityGet2DClipping(i.worldPosition.xy, _ClipRect);
if (xx > 0)
{
col = fixed4(1, 0, 0, 1);
}
else
{
col = fixed4(1, 1, 0, 1);
}
return col;
}
ENDCG
}
}
}
例子就应该这么简单。上面的shader是说,如果在区域内则是红色,否则使黄色。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIClipTest : MonoBehaviour
{
public Vector4 clipRect;
public MeshRenderer meshRenderer;
void Start()
{
meshRenderer = this.GetComponent<MeshRenderer>();
}
void Update()
{
SetColorPropertyBlock(meshRenderer);
}
private void SetColorPropertyBlock(Renderer renderer)
{
MaterialPropertyBlock properties = new MaterialPropertyBlock();
properties.SetVector("_ClipRect", clipRect);
renderer.SetPropertyBlock(properties);
}
}
一直往shader中塞数据。
观察其结果。
只有右上角为红色,因为此时区域是左下角为(0,0),右上角为(0.5,0.5)
如果是区域是(-0.5,-0.5)和(0.5,0.5)则全部是红色。
ok,结束。