问题描述
我有一个角色,每两秒钟更改其朝向(左右).在两秒钟之后,速度乘以-1,因此它改变了方向,但一直保持向右(->)
I've got a character that changes its facing (right or left) every two seconds. After that two seconds, the speed is multiplied by -1, so it changes its direction, but it just keeps going right (->)
这是我的代码:
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
在其本地空间而不是世界空间中转换对象.
That's because transform.Translate
translates the object in it's local space, not the world space.
当您执行以下操作时:
// The object will look at the opposite direction after this line
transform.rotation = Quaternion.LookRotation (Vector3.back);
speed *= -1;
您将对象翻转,然后要求您朝相反的方向前进.这样,物体将随后沿初始方向平移.
You flip your object and you ask to go in the opposite direction. Thus, the object will translate in the initial direction afterwards.
为解决您的问题,建议您不要更改speed
变量的值.
To fix your problem, I advise you to not change the value of the speed
variable.
尝试在相同的情况下想象自己:
Try to imagine yourself in the same situation :
- 向前走
- 旋转180度并向后走
最后,您沿同一方向继续"前进
In the end, you "continue" your path in the same direction
这是最终的方法:
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;
}
}
这篇关于角色不改变方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!