Unity3d 字符不改变方向
我有一个角色每两秒钟改变一次脸(右或左)。在这两秒钟之后,速度乘以-1,所以它改变了方向,但它只是继续向右(->) 这是我的密码:Unity3d 字符不改变方向,unity3d,Unity3d,我有一个角色每两秒钟改变一次脸(右或左)。在这两秒钟之后,速度乘以-1,所以它改变了方向,但它只是继续向右(->) 这是我的密码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyController : MonoBehaviour { public int speed = 2; void Start () { StartCorout
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour {
public int speed = 2;
void Start ()
{
StartCoroutine(Animate ());
}
void Update ()
{
float auto = Time.deltaTime * speed;
transform.Translate (auto, 0, 0);
}
IEnumerator Animate()
{
while (true) {
yield return new WaitForSeconds (2);
transform.rotation = Quaternion.LookRotation (Vector3.back);
speed *= -1;
yield return new WaitForSeconds (2);
transform.rotation = Quaternion.LookRotation (Vector3.forward);
speed *= -1;
}
}
}
这是因为
transform.Translate
在对象的局部空间而不是世界空间中转换对象
当您执行以下操作时:
// The object will look at the opposite direction after this line
transform.rotation = Quaternion.LookRotation (Vector3.back);
speed *= -1;
你翻转你的物体,并要求朝相反的方向移动。因此,对象随后将在初始方向上平移
为了解决您的问题,我建议您不要更改speed
变量的值
试着想象自己处于同样的情况:
IEnumerator Animate()
{
WaitForSeconds delay = new WaitForSeconds(2) ;
Quaterion backRotation = Quaternion.LookRotation (Vector3.back) ;
Quaterion forwardRotation = Quaternion.LookRotation (Vector3.forward) ;
while (true)
{
yield return delay;
transform.rotation = backRotation;
yield return delay;
transform.rotation = forwardRotation;
}
}
天才!谢谢,这真的很烦人,我想不出来。对不起,你能写下完整的方法吗|只需删除两个
speed*=-1代码>来自动画()好的,非常感谢,这个问题也让我很恼火,我不知道该怎么办@阿迪:我写了一些优化的完整函数;)