UGUI表现效果

色阶调整 Shader

Shader "Custom/ColorLevelsSurfaceShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)) = 0.5 _Metallic ("Metallic", Range(0,1)) = 0.0 _inBlack("Input Black", Range(0, 255)) = 0 _inGamma("Input Gamma", Range(0, 2)) = 1 _inWhite("Input White", Range(0, 255)) = 255 _outWhite("Output White", Range(0, 255)) = 255 _outBlack("Output Black", Range(0, 255)) = 0 } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Standard fullforwardshadows // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _Color; float _inBlack; float _inGamma; float _inWhite; float _outWhite; float _outBlack; float GetPixelLevel(float inPixel) { return (pow(((inPixel * 255.0) - _inBlack) / (_inWhite - _inBlack), _inGamma) * (_outWhite - _outBlack) + _outBlack) / 255.0; } void surf (Input IN, inout SurfaceOutputStandard o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; c.rgb = fixed3(GetPixelLevel(c.r), GetPixelLevel(c.g), GetPixelLevel(c.b)); o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }

multi_compile 提取颜色通道 Shader

Shader "Custom/ColorChannelSurfaceShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)) = 0.5 _Metallic ("Metallic", Range(0,1)) = 0.0 [Toggle(NoRedChannel)] _NoUseRedChannel("No Use Red Channel", Float) = 0 [Toggle(NoGreenChannel)] _NoUseGreenChannel("No Use Green Channel", Float) = 0 [Toggle(NoBlueChannel)] _NoUseBlueChannel("No Use Blue Channel", Float) = 0 } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Standard fullforwardshadows // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 #pragma multi_compile __ NoRedChannel #pragma multi_compile __ NoGreenChannel #pragma multi_compile __ NoBlueChannel sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _Color; void surf (Input IN, inout SurfaceOutputStandard o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; #ifdef NoRedChannel c.r = 0; #endif #ifdef NoGreenChannel c.g = 0; #endif #ifdef NoBlueChannel c.b = 0; #endif o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }

UV精灵动画Shader

Shader "Custom/AnimatedSpriteSurfaceShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)) = 0.5 _Metallic ("Metallic", Range(0,1)) = 0.0 _CellRowAmount("Cell Row Amount", float) = 1 _CellColumnAmount("Cell Column Amount", float) = 1 _Speed("Speed", Range(0.01, 32)) = 12 } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Standard fullforwardshadows // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _Color; float4 _MainTex_TexelSize; float _CellRowAmount; float _CellColumnAmount; float _Speed; void surf (Input IN, inout SurfaceOutputStandard o) { float2 spriteUV = IN.uv_MainTex; float cellUVRowPercentage = 1 / _CellRowAmount; float cellUVColumnPercentage = 1 / _CellColumnAmount; int index = fmod(_Time.y * _Speed, _CellRowAmount * _CellColumnAmount); int rowIndex = index / _CellColumnAmount; int columnIndex = index - (rowIndex * _CellColumnAmount);//fmod(index, _CellColumnAmount); float xValue = spriteUV.x / _CellColumnAmount; xValue += columnIndex * cellUVColumnPercentage; float yValue = (_CellRowAmount - 1 + spriteUV.y) / _CellRowAmount; yValue -= rowIndex * cellUVRowPercentage; spriteUV = float2(xValue, yValue); // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, spriteUV) * _Color; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }

循环UV滚动Shader

Shader "Custom/ScrollSurfaceShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)) = 0.5 _Metallic ("Metallic", Range(0,1)) = 0.0 _ScrollXSpeed("X Scroll Speed", Range(0, 10)) = 0.2 _ScrollYSpeed("Y Scroll Speed", Range(0, 10)) = 0.2 } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Standard fullforwardshadows // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _Color; fixed _ScrollXSpeed; fixed _ScrollYSpeed; void surf (Input IN, inout SurfaceOutputStandard o) { fixed scrollValue = fixed2(_ScrollXSpeed * _Time.y, _ScrollYSpeed * _Time.y); float2 scrolledUV = IN.uv_MainTex + scrollValue; scrolledUV = frac(scrolledUV); // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, scrolledUV) * _Color; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }

勾边Shader

注意:材质里面的纹理需要设置,_MainTex_TexelSize才能获取到正确数值。

以下代码改自builtin_shaders-5.3.2f1\DefaultResourcesExtra\UI\UI-Default.shader

Shader "Custom/UI/OutlineDefault"
{
    Properties
    {
        _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255

        _ColorMask ("Color Mask", Float) = 15

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0

        _OutlineColor("Outline Color", Color) = (1,1,1,1)
        _OutlineWidth("Outline Width", Float) = 2
        _Threshold("Threshold", Range(0, 1)) = 0.5
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
            CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"
#include "UnityUI.cginc"

#pragma multi_compile __ UNITY_UI_ALPHACLIP

            struct appdata_t
            {
float4 vertex   :
                POSITION;
float4 color    :
                COLOR;
float2 texcoord :
                TEXCOORD0;
            };

            struct v2f
            {
float4 vertex   :
                SV_POSITION;
fixed4 color    :
                COLOR;
half2 texcoord  :
                TEXCOORD0;
float4 worldPosition :
                TEXCOORD1;
            };

            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.worldPosition = IN.vertex;
                OUT.vertex = mul(UNITY_MATRIX_MVP, OUT.worldPosition);

                OUT.texcoord = IN.texcoord;

#ifdef UNITY_HALF_TEXEL_OFFSET
                OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);
#endif

                OUT.color = IN.color * _Color;
                return OUT;
            }

            sampler2D _MainTex;
            float4 _MainTex_TexelSize;

            float4 _OutlineColor;
            float _OutlineWidth;
            float _Threshold;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;

                color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);

#ifdef UNITY_UI_ALPHACLIP
                clip (color.a - 0.001);
#endif

                float width = _MainTex_TexelSize.z, height = _MainTex_TexelSize.w;

                if (color.a <= _Threshold)
                {
                    half2 dir[8] = { { 0,1 },{ 1,1 },{ 1,0 },{ 1,-1 },{ 0,-1 },{ -1,-1 },{ -1,0 },{ -1,1 } };
                    for (int i = 0; i < 8; i++)
                    {
                        float2 offset = float2(dir[i].x / width, dir[i].y / height);
                        offset *= _OutlineWidth;

                        half4 nearby = (tex2D(_MainTex, IN.texcoord + offset) + _TextureSampleAdd) * IN.color;
                        if (nearby.a > _Threshold)
                        {
                            color = _OutlineColor;
                            break;
                        }
                    }
                }

                return color;
            }
            ENDCG
        }
    }
}

 

圆角Shader

以下代码改自builtin_shaders-5.3.2f1\DefaultResourcesExtra\UI\UI-Default.shader

Shader "Custom/UI/RoundedDefault"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
        _Color("Tint", Color) = (1,1,1,1)

        _StencilComp("Stencil Comparison", Float) = 8
        _Stencil("Stencil ID", Float) = 0
        _StencilOp("Stencil Operation", Float) = 0
        _StencilWriteMask("Stencil Write Mask", Float) = 255
        _StencilReadMask("Stencil Read Mask", Float) = 255

        _ColorMask("Color Mask", Float) = 15

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip("Use Alpha Clip", Float) = 0

        _RoundedRadius("Rounded Radius", Range(0, 256)) = 64
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Stencil
        {
            Ref[_Stencil]
            Comp[_StencilComp]
            Pass[_StencilOp]
            ReadMask[_StencilReadMask]
            WriteMask[_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest[unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask[_ColorMask]

        Pass
        {
            CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"
#include "UnityUI.cginc"

#pragma multi_compile __ UNITY_UI_ALPHACLIP

            struct appdata_t
            {
float4 vertex   :
                POSITION;
float4 color    :
                COLOR;
float2 texcoord :
                TEXCOORD0;
            };

            struct v2f
            {
float4 vertex   :
                SV_POSITION;
fixed4 color :
                COLOR;
half2 texcoord  :
                TEXCOORD0;
float4 worldPosition :
                TEXCOORD1;
            };

            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;

            float _RoundedRadius;

            float4 _MainTex_TexelSize;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.worldPosition = IN.vertex;
                OUT.vertex = mul(UNITY_MATRIX_MVP, OUT.worldPosition);

                OUT.texcoord = IN.texcoord;

#ifdef UNITY_HALF_TEXEL_OFFSET
                OUT.vertex.xy += (_ScreenParams.zw - 1.0)*float2(-1,1);
#endif

                OUT.color = IN.color * _Color;
                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;

                color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);

#ifdef UNITY_UI_ALPHACLIP
                clip(color.a - 0.001);
#endif

                float width = _MainTex_TexelSize.z;
                float height = _MainTex_TexelSize.w;

                float x = IN.texcoord.x * width;
                float y = IN.texcoord.y * height;

                float r = _RoundedRadius;

                //左下角
                if (x < r && y < r)
                {
                    if ((x - r) * (x - r) + (y - r) * (y - r) > r * r)
                        color.a = 0;
                }

                //左上角
                if (x < r && y > (height - r))
                {
                    if ((x - r) * (x - r) + (y - (height - r)) * (y - (height - r)) > r * r)
                        color.a = 0;
                }

                //右下角
                if (x > (width - r) && y < r)
                {
                    if ((x - (width - r)) * (x - (width - r)) + (y - r) * (y - r) > r * r)
                        color.a = 0;
                }

                //右上角
                if (x > (width - r) && y > (height - r))
                {
                    if ((x - (width - r)) * (x - (width - r)) + (y - (height - r)) * (y - (height - r)) > r * r)
                        color.a = 0;
                }

                return color;
            }
            ENDCG
        }
    }
}

 

实现的功能就是点击一张图片,透明的区域会穿透。

using UnityEngine;
using UnityEngine.UI;

[DisallowMultipleComponent]
[RequireComponent(typeof(Image))]
[ExecuteInEditMode]
public class ImageRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
    public bool reversed;

    private Image image;

    void OnEnable()
    {
        image = GetComponent();
        image.type = Image.Type.Simple;
    }

    public bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        if (!enabled)
            return true;

        Sprite sprite = image.overrideSprite;
        if (sprite == null)
            return true;

        Vector2 local;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(image.rectTransform, screenPoint, eventCamera, out local);

        Rect rect = image.rectTransform.rect;

        // Convert to have lower left corner as reference point.
        local.x += image.rectTransform.pivot.x * rect.width;
        local.y += image.rectTransform.pivot.y * rect.height;

        float u = local.x / rect.width;
        float v = local.y / rect.height;

        try
        {
            if(!reversed)
                return sprite.texture.GetPixelBilinear(u, v).a != 0;
            else
                return sprite.texture.GetPixelBilinear(u, v).a == 0;
        }
        catch (UnityException e)
        {
            Debug.LogException(e);
        }

        return true;
    }
}
using UnityEngine;
using UnityEngine.UI;

[DisallowMultipleComponent]
[RequireComponent(typeof(RawImage))]
public class RawImageRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
    public bool reversed;

    private RawImage rawImage;

    void OnEnable()
    {
        rawImage = GetComponent();
    }

    public bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        if (!enabled)
            return true;

        Texture2D texture = rawImage.texture as Texture2D;
        if (texture == null)
            return true;

        Vector2 local;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rawImage.rectTransform, screenPoint, eventCamera, out local);

        Rect rect = rawImage.rectTransform.rect;

        // Convert to have lower left corner as reference point.
        local.x += rawImage.rectTransform.pivot.x * rect.width;
        local.y += rawImage.rectTransform.pivot.y * rect.height;

        Rect uvRect = rawImage.uvRect;
        float u = local.x / rect.width * uvRect.width + uvRect.x;
        float v = local.y / rect.height * uvRect.height + uvRect.y;

        try
        {
            if (!reversed)
                return texture.GetPixelBilinear(u, v).a != 0;
            else
                return texture.GetPixelBilinear(u, v).a == 0;
        }
        catch (UnityException e)
        {
            Debug.LogException(e);
        }

        return true;
    }
}

 

//UGUI对image控件检测鼠标按下和抬起

其中OnPointerDown方法需要类继承IPointerDownHandler接口,而OnPointerUp方法需要类继承IPointerUpHandler接口。

在UGUI中对image控件检测鼠标按下和抬起使用OnPointerDown和OnPointerUp方法 其中OnPointerDown方法需要类继承IPointerDownHandler接口,而OnPointerUp方法需要类继承IPointerUpHandler接口。

鼠标按住“开始”控件并下滑时,检测该控件的位置,当移动的距离超过一半时如果松开,控件会自动移动到背景控件下方,若为超过距离的一半,松开鼠标,控件会返回上端。 1. 为背景控件添加ScrollRect方法,并将content属性设置为开始控件。 2. 设置ScrollRect方法,勾选Vertical,使开始控件只能上下移动。 3. 通过代码控制开始控件的位置,判断不同位置控件的变化。 源代码如下

using UnityEngine;

using System.Collections;

using UnityEngine.UI;

using UnityEngine.EventSystems;

public class StartButton : MonoBehaviour,IPointerDownHandler,IPointerUpHandler

{

private Transform ButtonStart;

private Image ButtonImage;

private bool isPointerDown;

private Vector3 InitMousePos;

void Awake()

{

ButtonStart = this.transform.Find("Start").transform;

 ButtonImage=ButtonStart.GetComponent();

}

void Start()

{

ButtonStart.localPosition = new Vector3(ButtonStart.localPosition.x, 60f, ButtonStart.transform.localPosition.z);

InitMousePos = Vector3.zero;

}

void Update()

 {

UpdateButton();

}

//根据Y值来改变游戏状态

private void UpdateButton()

 {

if (isPointerDown)

 {

if (ButtonStart.localPosition.y > 60f || ButtonStart.localPosition.y < -60f)

 {

float newY = (Mathf.Abs(ButtonStart.localPosition.y) / ButtonStart.localPosition.y) * 60f;

if (newY <= 0)

 {

ButtonImage.color = new Color(104, 255, 0, 255);

}

ButtonStart.localPosition = new Vector3(ButtonStart.localPosition.x, newY, ButtonStart.transform.localPosition.z);

}

}

 Else

 {

 float y = ButtonStart.localPosition.y;

if (y <= 0)

{ ButtonStart.localPosition = new Vector3(ButtonStart.localPosition.x, -60f, ButtonStart.transform.localPosition.z);

ButtonImage.color = new Color(104, 255, 0, 255);

 }

else

{

ButtonStart.localPosition = new Vector3(ButtonStart.localPosition.x, 60f, ButtonStart.transform.localPosition.z);

 }

 if (ButtonStart.localPosition.y == -60f)

 {

this.GetComponent().enabled = false;

 StartCoroutine(WaitAndSkip());

 }

}

}

//控制场景等待、跳转

private IEnumerator WaitAndSkip()

{

yield return new WaitForSeconds(0.5f);

Application.LoadLevel(1);

}

//检测鼠标按下与抬起

public void OnPointerDown(PointerEventData eventData)

 {

isPointerDown = true;

}

public void OnPointerUp(PointerEventData eventData)

 {

 isPointerDown = false;

}

}

Image模糊效果

Shader "CustomUI/Default"

{

Properties

{

[PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}

_Color ("Tint", Color) = (1,1,1,1)

_StencilComp ("Stencil Comparison", Float) = 8

_Stencil ("Stencil ID", Float) = 0

_StencilOp ("Stencil Operation", Float) = 0

_StencilWriteMask ("Stencil Write Mask", Float) = 255

_StencilReadMask ("Stencil Read Mask", Float) = 255

 

_ColorMask ("Color Mask", Float) = 15

        //--------------add------------------

        _Distance ("Distance", Float) = 0.015

        //--------------add------------------

}

 

SubShader

{

Tags

{

"Queue"="Transparent"

"IgnoreProjector"="True"

"RenderType"="Transparent"

"PreviewType"="Plane"

"CanUseSpriteAtlas"="True"

}

Stencil

{

Ref [_Stencil]

Comp [_StencilComp]

Pass [_StencilOp]

ReadMask [_StencilReadMask]

WriteMask [_StencilWriteMask]

}

 

Cull Off

Lighting Off

ZWrite Off

ZTest [unity_GUIZTestMode]

Fog { Mode Off }

Blend SrcAlpha OneMinusSrcAlpha

ColorMask [_ColorMask]

 

Pass

{

CGPROGRAM

#pragma vertex vert

#pragma fragment frag

#include "UnityCG.cginc"

struct appdata_t

{

float4 vertex   : POSITION;

float4 color    : COLOR;

float2 texcoord : TEXCOORD0;

};

 

struct v2f

{

float4 vertex   : SV_POSITION;

fixed4 color    : COLOR;

half2 texcoord  : TEXCOORD0;

};

fixed4 _Color;

 

v2f vert(appdata_t IN)

{

v2f OUT;

OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);

OUT.texcoord = IN.texcoord;

#ifdef UNITY_HALF_TEXEL_OFFSET

OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);

#endif

OUT.color = IN.color * _Color;

return OUT;

}

 

sampler2D _MainTex;

            //--------------add------------------

            float _Distance;

            //--------------add------------------

fixed4 frag(v2f IN) : SV_Target

{

// //half4 color = tex2D(_MainTex, IN.texcoord) * IN.color;

// //clip (color.a - 0.01);

// //return color;

 

                //--------------add------------------

                float distance = _Distance;

                fixed4 computedColor = tex2D(_MainTex, IN.texcoord) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x + distance , IN.texcoord.y + distance )) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x + distance , IN.texcoord.y)) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x , IN.texcoord.y + distance )) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x - distance , IN.texcoord.y - distance )) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x + distance , IN.texcoord.y - distance )) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x - distance , IN.texcoord.y + distance )) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x - distance , IN.texcoord.y)) * IN.color;

                computedColor += tex2D(_MainTex, half2(IN.texcoord.x , IN.texcoord.y - distance )) * IN.color;

                computedColor = computedColor / 9;

                return computedColor;

                //--------------add------------------

}

ENDCG

}

}

}

UI上使用RenderTexture显示模型+AlphaBlend特效

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

 

public class SpriteFull : MonoBehaviour {

 

//设置SpriteRender和摄像机的距离

public float distance = 1.0f;

 

 

private SpriteRenderer spriteRenderer = null;

void Start()

{

spriteRenderer = GetComponent ();

spriteRenderer.material.renderQueue =2980; //这段代码非常重要!!!大家务必要加上,不然透明的渲染层级会出错

}

 

void Update()

{

Camera camera = Camera.main;

camera.transform.rotation = Quaternion.Euler (Vector3.zero);

 

float width = spriteRenderer.sprite.bounds.size.x;

float height = spriteRenderer.sprite.bounds.size.y;

 

float worldScreenHeight,worldScreenWidth;

//这里分别处理正交和非正交摄像机

if (camera.orthographic) {

worldScreenHeight = Camera.main.orthographicSize * 2.0f;

worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

} else {

worldScreenHeight = 2.0f * distance * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);

worldScreenWidth = worldScreenHeight * camera.aspect;

}

transform.localPosition = new Vector3 (camera.transform.position.x, camera.transform.position.y, distance);

transform.localScale = new Vector3 (worldScreenWidth / width, worldScreenHeight / height, 0f);

}

}

不规则按钮的响应区域

1.把按钮的image的RaycastTarget关闭勾选

2.在子节点创建新的gameObject挂上下面UIPolygon脚本。

3.编辑Polygon的区域即可。

using UnityEngine;

using System.Collections;

using UnityEngine.UI;

#if UNITY_EDITOR

using UnityEditor;

#endif

[RequireComponent(typeof(PolygonCollider2D))]

public class UIPolygon : Image

{

    private PolygonCollider2D _polygon = null;

    private PolygonCollider2D polygon

    {

        get{

            if(_polygon == null )

                _polygon = GetComponent();

            return _polygon;

        }

    }

    protected UIPolygon()

    {

        useLegacyMeshGeneration = true;

    }

    protected override void OnPopulateMesh(VertexHelper vh)

    {

        vh.Clear();

    }

    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)

    {

        return polygon.OverlapPoint( eventCamera.ScreenToWorldPoint(screenPoint));

    }

 

#if UNITY_EDITOR

    protected override void Reset()

    {

        base.Reset();

        transform.localPosition = Vector3.zero;

        float w = (rectTransform.sizeDelta.x *0.5f) + 0.1f;

        float h = (rectTransform.sizeDelta.y*0.5f)  + 0.1f;

        polygon.points = new Vector2[]

        {

            new Vector2(-w,-h),

            new Vector2(w,-h),

            new Vector2(w,h),

            new Vector2(-w,h)

          };

    }

#endif

}

#if UNITY_EDITOR

[CustomEditor(typeof(UIPolygon), true)]

public class UIPolygonInspector : Editor

{

    public override void OnInspectorGUI()

    {

    }

}

#endif

你可能感兴趣的:(Unity_UI相关)