1. 程式人生 > >【Unity3D】 DoTween實現飄字的效果

【Unity3D】 DoTween實現飄字的效果

Sequence.Append構建緩動序列,同時Join方法支援並行緩動。利用這個特性,可以實現ugui—Text的飄字緩動效果。

Append是在序列的末端插入一個Tweener,如果前面的Tweener都執行完了,就執行這個Tweener。

Join也是在序列末端插入一個Tweener,不同的是,這個Tweener將與前一個非Join加進來的Tweener並行執行。

飄字效果程式碼:

public static void FlyTo(Graphic graphic)
{
	RectTransform rt = graphic.rectTransform;
	Color c = graphic.color;
	c.a = 0;
	graphic.color = c;
	Sequence mySequence = DOTween.Sequence();
	Tweener move1 = rt.DOMoveY(rt.position.y + 50, 0.5f);
	Tweener move2 = rt.DOMoveY(rt.position.y + 100, 0.5f);
	Tweener alpha1 = graphic.DOColor(new Color(c.r, c.g, c.b, 1), 0.5f);
	Tweener alpha2 = graphic.DOColor(new Color(c.r, c.g, c.b, 0), 0.5f);
	mySequence.Append(move1);
	mySequence.Join(alpha1);
	mySequence.AppendInterval(1);
	mySequence.Append(move2);
	mySequence.Join(alpha2);
}

呼叫

Text text = gameObject.GetComponent<Text>();
FlyTo(text);

1.首先設定文字的alpha值為0

2.然後文字沿y軸向上緩動,同時alpha從0緩動到1,兩個Tweener同時進行

3.停留1秒鐘,讓玩家看清楚字寫的是什麼

4.文字繼續往上飄,同時alpha從1緩動到0,逐漸消失

效果:

有同學問,這個字型顏色漸變效果怎麼弄,這裡可以參考雨鬆MOMO的文章http://www.xuanyusong.com/archives/3471,但是要稍微修改設定color的部分,alpha值不能設進去,否則我們這裡的漸變效果就出不來了。程式碼我就貼出來吧。另外,再加個Outline的效果就很好看了。

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

namespace MyScripts
{
	[AddComponentMenu("UI/Effects/Gradient")]
	public class Gradient : BaseVertexEffect
	{
		[SerializeField]
		private Color32 topColor = Color.white;
		[SerializeField]
		private Color32 bottomColor = new Color32(255, 153, 0, 255);
		[SerializeField]
		private bool useGraphicAlpha = true;

		public override void ModifyVertices(List<UIVertex> vertexList)
		{
			if (!IsActive())
			{
				return;
			}

			int count = vertexList.Count;
			if (count > 0)
			{
				float bottomY = vertexList[0].position.y;
				float topY = vertexList[0].position.y;

				for (int i = 1; i < count; i++)
				{
					float y = vertexList[i].position.y;
					if (y > topY)
					{
						topY = y;
					}
					else if (y < bottomY)
					{
						bottomY = y;
					}
				}

				float uiElementHeight = topY - bottomY;

				for (int i = 0; i < vertexList.Count; )
				{
					ChangeColor(ref vertexList, i, topColor);
					ChangeColor(ref vertexList, i + 1, topColor);
					ChangeColor(ref vertexList, i + 2, bottomColor);
					ChangeColor(ref vertexList, i + 3, bottomColor);
					i += 4;
				}
			}
		}

		private void ChangeColor(ref List<UIVertex> verList, int i, Color32 color)
		{
			UIVertex uiVertex = verList[i];
			if (useGraphicAlpha)
			{
				uiVertex.color = new Color32(color.r, color.g, color.b, uiVertex.color.a);
			}
			else
			{
				uiVertex.color = color;
			}
			verList[i] = uiVertex;
		}
	}
}