在《【iTween】单点移动和旋转》(点击打开链接)和《【iTween】指定路径位移》(点击打开链接)我曾经介绍过iTween的使用,在iTween中同时做移动和旋转的动作是合法的,比如如下的代码:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
void Start()
{
iTween.MoveTo(gameObject, iTween.Hash("position", new Vector3(0, 0, 2), "easeType", "easeInCubic", "time", 1f, "loolType", "none"));
iTween.RotateTo(gameObject, iTween.Hash("rotation", new Vector3(0, 180, 0), "easeType", "easeInCubic", "time", 1f, "loolType", "none"));
}
}
对于一个在(0,0,0)的Cube运行结果如下:
但如果我希望这个正方体完成多个动作,比如移动到一个点之后,再经过旋转,然后又移动到另一个点,又旋转等一系列的动作序列。由于【iTween】指定路径位移》(点击打开链接)中的iTweenPath只提供的多点位置,此时你需要通过协程去完成。
如下代码是不行的:
因为iTween必须播完一个动画才能进行其它动画。也就是说,这段iTween在time这个属性中,定义1s的动作,你必须过了1s再才对其再下达另一个命令,但代码的一行一行的读取,瞬间就读完了,在Start()函数和Update()又不能被yield挂起,所以必须通过协程去完成。
有了《【Unity3D】协程Coroutine的运用》(点击打开链接)关于协程的思想,完成iTween定义个动作序列就简单了,如下的代码,就展示了如何完成一个iTween的动作序列:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
void Start()
{
StartCoroutine(iTween_coroutine());
}
IEnumerator iTween_coroutine()
{
iTween.MoveTo(gameObject, iTween.Hash("position", new Vector3(0, 0, 2), "easeType", "easeInCubic", "time", 1f, "loolType", "none"));
yield return new WaitForSeconds(1.0f);
iTween.RotateTo(gameObject, iTween.Hash("rotation", new Vector3(0, 180, 0), "easeType", "easeInCubic", "time", 1f, "loolType", "none"));
yield return new WaitForSeconds(1.0f);
iTween.MoveTo(gameObject, iTween.Hash("position", new Vector3(0, 0, -2), "easeType", "easeInCubic", "time", 1f, "loolType", "none"));
yield return new WaitForSeconds(1.0f);
iTween.RotateTo(gameObject, iTween.Hash("rotation", new Vector3(0, 0, 0), "easeType", "easeInCubic", "time", 1f, "loolType", "none"));
}
}
对于一个在(0,0,0)的Cube运行结果如下:
这就遵循了iTween组件,只能对已经iTween动作的对象,再次下达iTween动画指令的问题了。