游戏的UI开发中经常会遇到需要制作提示玩家,诱惑玩家注意或点击界面的某个控件的特效。粒子系统是一种解决方案,本文是介绍另外一种解决方案,用倾斜光线扫过控件或标题。效果如下图
思路其实很简单,核心就是对材质的某一层纹理进行uv平移,本例是平移光线纹理的x方向,如下图
本程序运用到U3D提供的纹理位移api material.SetTextureOffset,当光线离开主纹理后,隔200帧重新重右往左移动。程序如下。
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Collections;
public class FlashLight : MonoBehaviour
{
private UITexture tex;
float m_fOffset = -0.5f; //x方向的纹理位移
public int m_fSpeed = 2; //移动速度
bool m_bStartFlashing = true; //特效开关
void Awake()
{
tex = GetComponent<UITexture>();
SetTheTextureOffset(m_fOffset);
tex.material.SetFloat("_AlphaFactor", 1);
}
public void SetTheTextureOffset(float offset)
{
tex.material.SetTextureOffset("_LightTex", new Vector2(offset, 0));
}
public void SetLightFactor(float factor)
{
tex.material.SetFloat("_LightFactor", factor);
}
void Update()
{
if (m_bStartFlashing)
{
SetLightFactor(1);
SetTheTextureOffset(m_fOffset += m_fSpeed * 0.01f);
if (m_fOffset >= 0.5f)
{
m_fOffset = -0.5f;
SetLightFactor(0);
m_bStartFlashing = false;
StartCoroutine(CallBackInFrames(() => { m_bStartFlashing = true; }, 200));
}
}
}
IEnumerator CallBackInFrames(Action callback, int inFrames)
{
int n = 0;
while (n < inFrames)
{
yield return new WaitForFixedUpdate();
n += 1;
}
callback();
}
}
对应的shader如下。
Shader "Winter/FlashLight"
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" { }
_AlphaTex("AlphaTex",2D) = "white"{}
_LightTex("LightTex",2D) = "white"{}
_LightFactor("LightFactor",Float) = 1
_AlphaFactor("AlphaFactor",Float) = 1
}
SubShader
{
Tags
{
"Queue" = "Transparent+8"
}
Pass
{
Lighting Off
ZTest Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
sampler2D _LightTex;
sampler2D _AlphaTex;
float _LightFactor;
half4 _Color;
float _AlphaFactor;
struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float2 uv1 : TEXCOORD1;
};
half4 _MainTex_ST;
half4 _LightTex_ST;
half4 _AlphaTex_ST;
v2f vert (appdata_base v)
{
v2f o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX (v.texcoord, _MainTex);
o.uv1 = TRANSFORM_TEX(v.texcoord,_LightTex);
return o;
}
half4 frag (v2f i) : COLOR
{
half4 texcol = tex2D (_MainTex, i.uv);
half4 lightcol = tex2D(_LightTex,i.uv1);
half4 result = texcol + lightcol* _LightFactor;//这里用纹理叠加效果
result.a = tex2D(_AlphaTex,i.uv).r * _AlphaFactor;
return result;
}
ENDCG
}
}
}
场景的GameObject分布如下
运行后得出开头的特效效果。