NGUIPanel裁剪粒子特效
问题:项目遇到在选择角色列表 当我选中一个
表,特效出panel裁剪区域不被裁剪.
item时 显示外发光粒子特效,这时滑动列
解决方案:通过 UIPanel 的 finalClipRegion 换算成 unity3d 世界坐标系中的区域,然后
传递到粒子的 shader 中进行裁剪。代码如下:
//C#脚本 using System; using UnityEngine;
[RequireComponent(typeof(UIPanel))]
public class ParticleSystemClipper : MonoBehaviour {
const string ShaderName = \放在自己项目shader目录下
const float ClipInterval = 0.5f;
UIPanel m_targetPanel; Shader m_shader;
void Start() {
// find panel
m_targetPanel = GetComponent
if (m_targetPanel == null)
throw new ArgumentNullException(\ if (m_targetPanel.clipping != UIDrawCall.Clipping.SoftClip)
throw new InvalidOperationException(\
m_shader = Shader.Find(ShaderName);
if (!IsInvoking(\
InvokeRepeating(\ }
Vector4 CalcClipArea() {
var clipRegion = m_targetPanel.finalClipRegion;
Vector4 nguiArea = new Vector4() {
x = clipRegion.x - clipRegion.z / 2, y = clipRegion.y - clipRegion.w / 2, z = clipRegion.x + clipRegion.z / 2, w = clipRegion.y + clipRegion.w / 2 };
var uiRoot = LuaUtils.UIRoot.GetComponent
float temp = h / uiRoot.manualHeight;
return new Vector4() {
x = pos.x + nguiArea.x * temp, y = pos.y + nguiArea.y * temp, z = pos.x + nguiArea.z * temp, w = pos.y + nguiArea.w * temp }; }
void Clip() {
Vector4 clipArea = CalcClipArea();
var particleSystems = this.GetComponentsInChildren
for (int i = 0; i < particleSystems.Length; i++) {
var ps = particleSystems[i]; var mat = ps.renderer.material;
if (mat.shader.name != ShaderName) mat.shader = m_shader;
mat.SetVector(\ } }
void OnDestroy() {
CancelInvoke(\ } }
//Shader脚本
Shader \{
Properties {
_TintColor (\ _MainTex (\ _Area (\ }
Category {
Tags { \ Blend SrcAlpha One AlphaTest Greater .01 ColorMask RGB Cull Off Lighting Off ZWrite Off
Fog { Color (0,0,0,0) }
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert #pragma fragment frag
#pragma multi_compile_particles
#include \
sampler2D _MainTex; fixed4 _TintColor; float4 _Area;
struct appdata_t {
float4 vertex : POSITION; fixed4 color : COLOR;
float2 texcoord : TEXCOORD0; };
struct v2f {
float4 vertex : SV_POSITION; fixed4 color : COLOR;
float2 texcoord : TEXCOORD0; float2 worldPos : TEXCOORD1; };
float4 _MainTex_ST;
v2f vert (appdata_t v) {
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.texcoord = TRANSFORM_TEX(v.texcoord,_MainTex); o.color = v.color;
o.worldPos = mul(_Object2World, v.vertex).xy; return o; }
fixed4 frag (v2f i) : SV_Target {
bool inArea = i.worldPos.x >= _Area.x && i.worldPos.x <= _Area.z && i.worldPos.y >= _Area.y && i.worldPos.y <= _Area.w;
return inArea? 2.0f * i.color * _TintColor * tex2D(_MainTex, i.texcoord) : fixed4(0,0,0,0);
}
ENDCG } } } }