Unity插件之DoTween案例分析

Unity动画与交互案例
本文通过Unity中的多个案例,如基本动画、跟随目标、材质变化、路径动画、序列动画及UI特效,展示了如何使用DOTween插件进行物体移动、旋转、颜色渐变等动画效果制作,同时介绍了拖动物体和响应鼠标事件的方法。

案例分析

01.Basics

Code:

using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Basics : MonoBehaviour
{
	public Transform redCube, greenCube, blueCube, purpleCube;

	IEnumerator Start()
	{
		// Start after one second delay (to ignore Unity hiccups(打嗝) when activating Play mode in Editor)
		yield return new WaitForSeconds(1);

		// Let's move the red cube TO 0,4,0 in 2 seconds
		redCube.DOMove(new Vector3(0,4,0), 2);

		// Let's move the green cube FROM 0,4,0 in 2 seconds
		greenCube.DOMove(new Vector3(0,4,0), 2).From();
		
		// Let's move the blue cube BY 0,4,0 in 2 seconds 相对位置
		blueCube.DOMove(new Vector3(0,4,0), 2).SetRelative();

		// Let's move the purple cube BY 6,0,0 in 2 seconds
		// and also change its color to yellow.
		// To change its color, we'll have to use its material as a target (instead than its transform).
		purpleCube.DOMove(new Vector3(6,0,0), 2).SetRelative();
		// Also, let's set the color tween to loop infinitely forward and backwards
                //在紫色和黄色之间yoyo球
		purpleCube.GetComponent<Renderer>().material.DOColor(Color.yellow, 2).SetLoops(-1, LoopType.Yoyo);
	}
}

02.Follow

Code:

DragTarget .cs
using UnityEngine;
using System.Collections;

public class DragTarget : MonoBehaviour
{
	Transform t;
	Camera mainCam;

	void Start()
	{
		t = this.transform;
		mainCam = Camera.main;
	}

	void OnMouseDrag()
	{
		Vector2 mousePos = Input.mousePosition;
        //以相机为起点到物体的位置
        float distance = mainCam.WorldToScreenPoint(t.position).z;
        //屏幕坐标到世界坐标
        t.position = mainCam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, distance));
    }
}
Follow.cs
using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Follow : MonoBehaviour
{
	public Transform target; // Target to follow
	Vector3 targetLastPos;
	Tweener tween;

	void Start()
	{
		// First create the "move to target" tween and store it as a Tweener.
		// In this case I'm also setting autoKill to FALSE so the tween can go on forever
		// (otherwise it will stop executing if it reaches the target)
		tween = transform.DOMove(target.position, 2).SetAutoKill(false);
		// Store the target's last position, so it can be used to know if it changes
		// (to prevent changing the tween if nothing actually changes)
		targetLastPos = target.position;
	}

	void Update()
	{
		// Use an Update routine to change the tween's endValue each frame
		// so that it updates to the target's position if that changed
		if (targetLastPos == target.position) return;
		// Add a Restart in the end, so that if the tween was completed it will play again
		tween.ChangeEndValue(target.position, true).Restart();
		targetLastPos = target.position;
	}
}

03.Materials

Code: 

Materials.cs 
using UnityEngine;
using DG.Tweening;

public class Materials : MonoBehaviour
{
	public GameObject target;
	public Color toColor;

	Tween colorTween, emissionTween, offsetTween;

	void Start()
	{
		// NOTE: all tweens will be created in a paused state, so they can be toggled via the UI

		// Store the material, since we will tween that
		Material mat = target.GetComponent<Renderer>().material;

		// COLOR
		colorTween = mat.DOColor(toColor, 1).SetLoops(-1, LoopType.Yoyo).Pause();

		// EMISSION
		// Note that the float value you see in Unity's inspector, next to the emission's color,
		// doesn't really exist in the shader (it's generated by Unity's inspector and applied to the material's color),
		// se we have to tween the full _EmissionColor.
		emissionTween = mat.DOColor(new Color(0, 0, 0, 0), "_EmissionColor", 1).SetLoops(-1, LoopType.Yoyo).Pause();

		// OFFSET
		// In this case we set the loop to Incremental and the ease to Linear, because it's cooler
		offsetTween = mat.DOOffset(new Vector2(1, 1), 1).SetEase(Ease.Linear).SetLoops(-1, LoopType.Incremental).Pause();
	}

	// Toggle methods (called by UI events)

	public void ToggleColor()
	{
		colorTween.TogglePause();
	}

	public void ToggleEmission()
	{
		emissionTween.TogglePause();
	}

	public void ToggleOffset()
	{
		offsetTween.TogglePause();
	}
}

04.Paths:过上车功能

Code:

//这是插件里面的枚举类型。
public enum PathType
    {
        //
        // 摘要:
        //     Linear, composed of straight segments between each waypoint
        Linear = 0,
        //
        // 摘要:
        //     Curved path (which uses Catmull-Rom curves)
        CatmullRom = 1
    }
using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Paths : MonoBehaviour
{
	public Transform target;
	public PathType pathType = PathType.CatmullRom;
	public Vector3[] waypoints = new[] {
		new Vector3(4, 2, 6),
		new Vector3(8, 6, 14),
		new Vector3(4, 6, 14),
		new Vector3(0, 6, 6),
		new Vector3(-3, 0, 0)
	};

	void Start()
	{
        // Create a path tween using the given pathType, Linear or CatmullRom (curved).
        // Use SetOptions to close the path 设为true,则最后一点和第一点重合
        // and SetLookAt to make the target orient to the path itself 
        //上一句为使目标朝向路径本身
        Tween t = target.DOPath(waypoints, 4, pathType)
            .SetOptions(true)
			.SetLookAt(0.001f);
		// Then set the ease to Linear and use infinite loops
		t.SetEase(Ease.Linear).SetLoops(-1);
	}
}

05.Sequences:悠悠球

using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Sequences : MonoBehaviour
{
	public Transform cube;
	public float duration = 4;

	IEnumerator Start()
	{
		// Start after one second delay (to ignore Unity hiccups when activating Play mode in Editor)
		yield return new WaitForSeconds(1);

		// Create a new Sequence.
		// We will set it so that the whole duration is 6
		Sequence s = DOTween.Sequence();
		// Add an horizontal relative move tween that will last the whole Sequence's duration
		s.Append(cube.DOMoveX(6, duration).SetRelative().SetEase(Ease.InOutQuad));
		// Insert a rotation tween which will last half the duration
		// and will loop forward and backward twice
		s.Insert(0, cube.DORotate(new Vector3(0, 45, 0), duration / 2).SetEase(Ease.InQuad).SetLoops(2, LoopType.Yoyo));
		// Add a color tween that will start at half the duration and last until the end
		s.Insert(duration / 2, cube.GetComponent<Renderer>().material.DOColor(Color.yellow, duration / 2));
		// Set the whole Sequence to loop infinitely forward and backwards
		s.SetLoops(-1, LoopType.Yoyo);
	}
}

06.UGUI,UI特效

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using DG.Tweening;

public class UGUI : MonoBehaviour
{
	public Image dotweenLogo, circleOutline;
	public Text text, relativeText, scrambledText;
	public Slider slider;

	void Start()
	{
		// All tweens are created in a paused state (by chaining to them a final Pause()),
		// so that the UI Play button can activate them when pressed.
		// Also, the ones that don't loop infinitely have the AutoKill property set to FALSE,
		// so they won't be destroyed when complete and can be resued by the RESTART button

		// Animate the fade out of DOTween's logo
		dotweenLogo.DOFade(0, 1.5f).SetAutoKill(false).Pause();

		// Animate the circle outline's color and fillAmount
		circleOutline.DOColor(RandomColor(), 1.5f).SetEase(Ease.Linear).Pause();
		circleOutline.DOFillAmount(0, 1.5f).SetEase(Ease.Linear).SetLoops(-1, LoopType.Yoyo)
			.OnStepComplete(()=> {
				circleOutline.fillClockwise = !circleOutline.fillClockwise;
				circleOutline.DOColor(RandomColor(), 1.5f).SetEase(Ease.Linear);
			})
			.Pause();

		// Animate the first text...
		text.DOText("This text will replace the existing one", 2).SetEase(Ease.Linear).SetAutoKill(false).Pause();
		// Animate the second (relative) text...
		relativeText.DOText(" - This text will be added to the existing one", 2).SetRelative().SetEase(Ease.Linear).SetAutoKill(false).Pause();
		// Animate the third (scrambled) text...
		scrambledText.DOText("This text will appear from scrambled chars", 2, true, ScrambleMode.All).SetEase(Ease.Linear).SetAutoKill(false).Pause();

		// Animate the slider
		slider.DOValue(1, 1.5f).SetEase(Ease.InOutQuad).SetLoops(-1, LoopType.Yoyo).Pause();
	}

	// Called by PLAY button OnClick event. Starts all tweens
	public void StartTweens()
	{
		DOTween.PlayAll();
                // 开始全部
	}

	// Called by RESTART button OnClick event. Restarts all tweens
	public void RestartTweens()
	{
		DOTween.RestartAll();
                // 重启全部
	}

	// Returns a random color
	Color RandomColor()
	{
		return new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
	}
}

 

 

 

==》》添加:拖动物体的C#方法:

Drag:

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

public class Drag : MonoBehaviour {

    Transform t;
    Camera mainCam;
    Vector3 offset;
    
	void Start () {
        t = this.transform;
        mainCam = Camera.main;
	}

    private void OnMouseDown()
    {
        Vector2 mousPos = Input.mousePosition;
        float distance = mainCam.WorldToScreenPoint(t.transform.position).z;
        Vector3 worldPos = mainCam.ScreenToWorldPoint(new Vector3(mousPos.x, mousPos.y, distance));
        offset = t.position - worldPos;
    }

    private void OnMouseDrag()
    {
        Vector2 mousPos = Input.mousePosition;
        float distance = mainCam.WorldToScreenPoint(t.transform.position).z;
        t.position = mainCam.ScreenToWorldPoint(new Vector3(mousPos.x, mousPos.y, distance)) + offset;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kerven_HKW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值