欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

Unity3D Shader实现扫描显示效果

时间:2021-08-04 08:33:44|栏目:.NET代码|点击:

本文实例为大家分享了Unity3D Shader实现扫描显示的具体代码,供大家参考,具体内容如下

通过Shader实现,从左向右的扫描显示,可自定义扫描颜色、宽度、速度。

效果图如下

编辑器界面如下

Shader源码如下

Shader "XM/ScanEffect"
{
 Properties
 {
 _MainTex("Main Tex", 2D) = "white"{}
 _lineColor("Line Color", Color) = (0,0,0,0)
 _lineWidth("Line width", Range(0, 1.0)) = 0.1
 _rangeX("Range X", Range(0,1.0)) = 1.0
 }

 SubShader
 {
 Tags {
 "Queue" = "Transparent"
 }

 ZWrite Off
 Blend SrcAlpha OneMinusSrcAlpha
 Cull back

 Pass
 {
 CGPROGRAM

 #pragma vertex vert
 #pragma fragment frag

 #include "Lighting.cginc"

 sampler2D _MainTex;
 float4 _MainTex_ST;
 float4 _lineColor;
 float _lineWidth;
 float _rangeX;

 struct a2v
 {
 float4 vertex : POSITION;
 float4 texcoord : TEXCOORD0;
 };

 struct v2f
 {
 float4 pos : SV_POSITION;
 float2 uv : TEXCOORD0;
 };

 v2f vert(a2v v)
 {
 v2f o;
 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
 o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
 return o;
 }

 fixed4 frag(v2f i) : SV_TARGET
 {
 fixed4 col = tex2D(_MainTex, i.uv);

 if(i.uv.x > _rangeX)
 {
 clip(-1);
 }
 else if (i.uv.x > _rangeX - _lineWidth)
 {
 float offsetX = i.uv.x - _rangeX +_lineWidth;
 fixed xAlpha = offsetX / _lineWidth;
 col = col * (1 - xAlpha) + _lineColor * xAlpha;
 }


 return col;
 }

 ENDCG
 }
 }

 FallBack "Diffuse"
}

代码调用如下

using UnityEngine;
using System.Collections;
public class ScanEffect : MonoBehaviour
{
 //默认扫描线的宽
 [Range(0,1)]
 public float _defaultLineW = 0.2f;
 //扫描的速度
 [Range(0, 1)]
 public float _showSpeed = 0.02f;

 private MeshRenderer _render;

 private void Awake()
 {
 _render = GetComponent<MeshRenderer>();
 SetX(0);
 SetLineWidth(0);
 }

 public void SetLineWidth(float val)
 {
 _render.material.SetFloat("_lineWidth", val);
 }
 public void SetX(float val)
 {
 _render.material.SetFloat("_rangeX", val);
 }

 public void Show()
 {
 StopCoroutine("Showing");
 StartCoroutine("Showing");
 }
 public void Hide()
 {
 StopCoroutine("Showing");

 SetX(0);
 SetLineWidth(0);
 }

 private IEnumerator Showing()
 {
 float deltaX = 0;
 float deltaWidth = _defaultLineW;

 SetX(deltaX);
 SetLineWidth(deltaWidth);

 while (true)
 {
 if (deltaX != 1)
 {
 deltaX = Mathf.Clamp01(deltaX + _showSpeed);
 SetX(deltaX);
 }
 else
 {
 if (deltaWidth != 0)
 {
 deltaWidth = Mathf.Clamp01(deltaWidth - _showSpeed);
 SetLineWidth(deltaWidth);
 }
 else
 {
 break;
 }
 }
 yield return new WaitForEndOfFrame();
 }
 }


 public void OnGUI()
 {
 if (GUILayout.Button("Show"))
 {
 Show();
 }
 if (GUILayout.Button("Hide"))
 {
 Hide();
 }
 }
}

上一篇:C# 如何判断两个文件内容是否相同的方法

栏    目:.NET代码

下一篇:unity android设备上查看log输出方式

本文标题:Unity3D Shader实现扫描显示效果

本文地址:http://www.codeinn.net/misctech/164145.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有