来回旋转游戏对象

Abd*_*023 2 c# rotation euler-angles unity-game-engine

我想在 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);

    }
}
Run Code Online (Sandbox Code Playgroud)

它总是卡在 360 度左右的中间。帮助?

Pro*_*mer 5

就像来回移动GameObject一样,您可以使用 来来回旋转 GameObject Mathf.PingPong。这就是它的用途。它将返回01之间的值。您可以将该值传递给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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

使用协程方法,您可以使用它来确定每次旋转的结束。

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;
}
Run Code Online (Sandbox Code Playgroud)