首页 > 解决方案 > transform.rotate(vector3.forward * Time.deltatime) 正在旋转对象的底部,而不是中心

问题描述

我是 Unity 新手,正在开发一款火箭在横向滚动迷宫中上下飞行的游戏。简单的。问题是以下代码使我的火箭在底部而不是中心旋转。这类似于如果您要统一旋转“枢轴”模式而不是“中心”。

        private void Rotate(){

        float rotationMultiple = Time.deltaTime * rotationSpeed;
        rigidBody.freezeRotation = true;

        if (Input.GetKey(KeyCode.LeftArrow)){
             transform.Rotate(Vector3.forward * rotationMultiple);
        }
        else if(Input.GetKey(KeyCode.RightArrow)){
             transform.Rotate(Vector3.back * rotationMultiple);
        }

        rigidBody.freezeRotation = false;
    }

当我试图掌握事情的窍门时,你的帮助意义重大。

标签: c#unity3dtransform

解决方案


为了围绕对象的中心旋转,使用Renderer.boundsBounds.center获取中心点并Transform.RotateAround围绕中心点旋转变换。

您当前正在使用欧拉角来旋转变换,但由于您的欧拉角向量只有一个非零分量,RotateAround如果您保持轴并rotationMultiple分开,我们可以将它们用作轴参数:

private rend;

Start() 
{
    rend = GetComponent<Renderer>();
}

private void Rotate(){

    Vector3 centerPoint = rend.bounds.center;

    float rotationMultiple = Time.deltaTime * rotationSpeed;
    rigidBody.freezeRotation = true;

    if (Input.GetKey(KeyCode.LeftArrow)){
         transform.RotateAround(centerPoint, Vector3.forward, rotationMultiple);
    }
    else if(Input.GetKey(KeyCode.RightArrow)){
         transform.RotateAround(centerPoint, Vector3.back, rotationMultiple);
    }

    rigidBody.freezeRotation = false;
}

请注意,如果渲染器的形状/大小发生变化,中心的位置可能会发生变化。


推荐阅读