UnityGet2DClipping函数解读

这个函数颇费我的脑力,都怪国内的博客写的跟屎样,都是抄写,没有一个自己的原创和感悟,下面我来讲下这个函数的真正意义。

参考: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,结束。

  • 19
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值