Unity Shader实现跳动的心脏

来源:互联网 发布:易语言编程代码大全 编辑:程序博客网 时间:2024/04/28 10:45



之前没有学shader的时候,看着别人做出来的效果,感觉好厉害的样子。


最近几天在恶补shader,学了点皮毛后就发现,这东西简单的很...


不啰嗦,直接进入正题:


思路:

1,在shader中设置两个变量,_WidthFactor和_HeightFactor,用来接收脚本中传递的参数,计算顶点的扩张幅度

2,在脚本中设置两条曲线AnimationCurve,分别设置定点的扩张幅度


思路很简单,直接上代码


Shader:

Shader "MyShader/Effect/Heart"{Properties{_MainTex ("Texture", 2D) = "white" {}_HeightFactor("HeightFactor",Range(0,0.5))=0_WidthFactor("WidthFactor",Range(0,0.5))=0.2}SubShader{Tags { "RenderType"="Opaque" }LOD 100Blend SrcAlpha OneMinusSrcAlphaPass{CGPROGRAM#pragma vertex vert#pragma fragment frag// make fog work#pragma multi_compile_fog#include "UnityCG.cginc"struct appdata{float4 vertex : POSITION;float2 uv : TEXCOORD0;};struct v2f{float2 uv : TEXCOORD0;UNITY_FOG_COORDS(1)float4 vertex : SV_POSITION;};sampler2D _MainTex;float4 _MainTex_ST;fixed _HeightFactor;fixed _WidthFactor;v2f vert (appdata v){v2f o;float2 xy = float2(v.vertex.x*(1 - _WidthFactor), v.vertex.y*(1 - _HeightFactor));float4 vertex = float4(xy,v.vertex.z,v.vertex.w);o.vertex = mul(UNITY_MATRIX_MVP, vertex);o.uv = TRANSFORM_TEX(v.uv, _MainTex);UNITY_TRANSFER_FOG(o,o.vertex);return o;}fixed4 frag (v2f i) : SV_Target{fixed4 col = tex2D(_MainTex, i.uv);return col;}ENDCG}}}

重点就是三行代码

float2 xy = float2(v.vertex.x*(1 - _WidthFactor), v.vertex.y*(1 - _HeightFactor));float4 vertex = float4(xy,v.vertex.z,v.vertex.w);o.vertex = mul(UNITY_MATRIX_MVP, vertex);

下面是C#控制脚本:

using UnityEngine;using System.Collections;public class Heart : MonoBehaviour {[SerializeField]public AnimationCurve width;[SerializeField]public AnimationCurve height;private UIWidget mUIwg;private Material mMat;// Use this for initializationvoid Start () {mUIwg = gameObject.GetComponent<UIWidget>();}// Update is called once per framevoid Update () {float time = Time.time % 1.0f;SetShaderArg(width.Evaluate(time),height.Evaluate(time));}bool SetShaderArg(float w,float h){if (mUIwg){if (mUIwg.drawCall==null)return false;mMat = mUIwg.drawCall.dynamicMaterial;mMat.SetFloat("_WidthFactor",w);mMat.SetFloat("_HeightFactor", h);return true;}return false;}}

两条曲线的设置:




本来第一种方案是想通过控制uv来实现的,但是想到控制定点,计算量会不会更小呢。特别是在UI中,定点就那么几个。(一些自以为是的想法,不知道对不对...欢迎指正)。


shader也没那么难,入门了一样简单...

欢迎大家一起学习交流,我是‘Hello 光头’!

转载请注明“Hello 光头原创”

QQ:1009570451

0 0
原创粉丝点击