之前没有学shader的时候,看着别人做出来的效果,感觉好厉害的样子。
最近几天在恶补shader,学了点皮毛后就发现,这东西简单的很...
不啰嗦,直接进入正题:
思路:
1,在shader中设置两个变量,_WidthFactor和_HeightFactor,用来接收脚本中传递的参数,计算顶点的扩张幅度
2,在脚本中设置两条曲线AnimationCurve,分别设置定点的扩张幅度
思路很简单,直接上代码
Shader:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63Shader "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 100 Blend SrcAlpha OneMinusSrcAlpha Pass { 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 } } }
重点就是三行代码
复制代码
1
2
3float2 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#控制脚本:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41using 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 initialization void Start () { mUIwg = gameObject.GetComponent<UIWidget>(); } // Update is called once per frame void 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
最后
以上就是健壮小蝴蝶最近收集整理的关于Unity Shader实现跳动的心脏的全部内容,更多相关Unity内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复