c# - 来回旋转游戏对象

标签 c# unity3d rotation euler-angles

我想在 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 .这就是它的用途。它将返回 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);
}

编辑:

随着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/

相关文章:

jQuery 插件可以在不反转内容的情况下执行旋转/翻转动画?

CSS 边框旋转

c# - jQuery Ajax、MVC 和查询字符串

c# - 无法从 Unity 游戏中嵌入的 Nancy REST 服务器获取 POST 正文

unity3d - 如何在unity3d中改变 Canvas 的大小

android - 可绘制限定符,位图在 HTC with Android 4+ 屏幕旋转后未正确更改

c# - 在 IIS8 中部署时缓存不起作用

c# - 使用 Visual C# 在多个 Windows 窗体应用程序中形成关闭事件

c# - 使用 LINQ to C# 的最佳模式是什么

android - 使用 Unity 发送 TCP