我想在 Y 轴上在 90,-90 之间来回旋转一个对象。问题是我可以在编辑器中将对象设置为 -90,但是当我运行项目时 -90 突然变成 270。无论如何,这是我正在使用的代码:
void Update()
{
if (transform.eulerAngles.y >= 270)
{
transform.Rotate(Vector3.up * speed * Time.deltaTime);
}
else if (transform.eulerAngles.y <= 90)
{
transform.Rotate(Vector3.up * -speed * Time.deltaTime);
}
}
它总是卡在 360 度左右的中间。帮忙?
最佳答案
就像moving GameObject来回旋转,可以用Mathf.PingPong
来回旋转GameObject .这就是它的用途。它将返回 0 和 1 之间的值。您可以将该值传递给 Vector3.Lerp
并生成执行旋转所需的 eulerAngle。
这也可以通过协程来完成,但是 Mathf.PingPong
如果您不需要知道何时到达目的地,则应使用。如果您想知道何时到达旋转目的地,则应使用协程。
public float speed = 0.36f;
Vector3 pointA;
Vector3 pointB;
void Start()
{
//Get current position then add 90 to its Y axis
pointA = transform.eulerAngles + new Vector3(0f, 90f, 0f);
//Get current position then substract -90 to its Y axis
pointB = transform.eulerAngles + new Vector3(0f, -90f, 0f);
}
void Update()
{
//PingPong between 0 and 1
float time = Mathf.PingPong(Time.time * speed, 1);
transform.eulerAngles = Vector3.Lerp(pointA, pointB, time);
}
编辑:
随着coroutine可用于确定每次旋转结束的方法。
public GameObject objectToRotate;
public float speed = 0.36f;
Vector3 pointA;
Vector3 pointB;
void Start()
{
//Get current position then add 90 to its Y axis
pointA = transform.eulerAngles + new Vector3(0f, 90f, 0f);
//Get current position then substract -90 to its Y axis
pointB = transform.eulerAngles + new Vector3(0f, -90f, 0f);
objectToRotate = this.gameObject;
StartCoroutine(rotate());
}
IEnumerator rotate()
{
while (true)
{
//Rotate 90
yield return rotateObject(objectToRotate, pointA, 3f);
//Rotate -90
yield return rotateObject(objectToRotate, pointB, 3f);
//Wait?
//yield return new WaitForSeconds(3);
}
}
bool rotating = false;
IEnumerator rotateObject(GameObject gameObjectToMove, Vector3 eulerAngles, float duration)
{
if (rotating)
{
yield break;
}
rotating = true;
Vector3 newRot = gameObjectToMove.transform.eulerAngles + eulerAngles;
Vector3 currentRot = gameObjectToMove.transform.eulerAngles;
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
gameObjectToMove.transform.eulerAngles = Vector3.Lerp(currentRot, newRot, counter / duration);
yield return null;
}
rotating = false;
}
关于c# - 来回旋转游戏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43628472/