- 我们可以在协程里面实现短暂的时间间隔,然后实现一个动画效果,代码如下
- 注意 yield new return null 是暂停一帧
- 陷阱实现上下移动动画
/// <summary>
/// 使用协程生成动画
/// </summary>
/// <returns></returns>
private IEnumerator Up()
{
while (true)
{
sonTransform.position = Vector3.Lerp(sonTransform.position, targetPos, Time.deltaTime * 50);
yield return null; //暂停一帧
}
}
private IEnumerator Down()
{
while (true)
{
sonTransform.position = Vector3.Lerp(sonTransform.position, normalPos, Time.deltaTime * 50);
yield return null;
}
}
private IEnumerator UpAndDown()
{
while (true)
{
StopCoroutine("Down");
StartCoroutine("Up");
yield return new WaitForSeconds(2.0f);
StopCoroutine("Up");
StartCoroutine("Down");
yield return new WaitForSeconds(2.0f);
}
}
//当按动按钮的时候,启动动画
void Update () {
if(Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(WallOpen(wall1_Transform));
}
if (Input.GetKeyDown(KeyCode.B))
{
StartCoroutine(WallOpen(wall2_Transform));
}
}
//协程实现动画效果
IEnumerator WallOpen(Transform wall)
{
while(wall.position.y > -2.1f)
{
wall.position = new Vector3(wall.position.x,wall.position.y - 0.1f, wall.position.z);
yield return new WaitForSeconds(0.05f);
}
}