Unity相机旋转

时间:2014-05-27 12:47:27

标签: c# camera rotation unity3d

我在我的场景中有一台相机,我正在使用第三方设备进行控制。如果我旋转设备,向前倾斜等等,我的相机会复制相同的动作。然而,我一直在努力解决如何始终确保我的相机面向前方并向前移动,尽管Y旋转。

例如,我的相机从点0,0,0开始,旋转值相同。如果我将相机旋转90度(任一侧)并向前移动相机,我的视图现在会向侧面移动。我怎样才能让我的相机朝向哪里,这是我的前进方向?

到目前为止,这是我的代码:

private void MoveForward()
{
    Debug.Log("yaw: " + yaw + " pitch: " + pitch + " roll: " + roll);

    if( pitch > maxPitch.x && pitch < maxPitch.y && reversePitch == false) 
    {
        camera.rigidbody.AddForce(0, 0,-pitch);
    //  camera.transform.position += new Vector3(0,0, -pitch);
    }
    else if ( pitch > maxPitch.x && pitch < maxPitch.y && reversePitch == true)
    {
        camera.rigidbody.AddForce(0, 0, pitch);
    //  camera.transform.position += new Vector3(0,0, pitch);
    }
    else
    {
        camera.rigidbody.velocity = Vector3.zero;
    //  camera.transform.position = new Vector3(0,0,0);
    }
}

private void MoveSideways()
{
    if( roll > maxRoll.x && roll < maxRoll.y && reverseRoll == false)
    {
        camera.rigidbody.AddForce( roll, 0, 0);

    }
    else if ( roll < maxRoll.x && roll > maxRollNegative && reverseRoll == false)
    {
        camera.rigidbody.AddForce( roll, 0 ,0);
    }
    else if( roll > maxRoll.x && roll < maxRoll.y && reverseRoll == true)
    {
        camera.rigidbody.AddForce( -roll, 0, 0);
    }
    else if ( roll < maxRoll.x && roll > maxRollNegative && reverseRoll == true)
    {
        camera.rigidbody.AddForce( -roll, 0 ,0);
    }
    else
    {
        camera.rigidbody.velocity = Vector3.zero;
    }
}


private void RotateAround()
{
    if(reverseYaw == true)
    {
        target = Quaternion.Euler(0, yaw,0);
    }
    else
    {
        target = Quaternion.Euler(0, -yaw,0);
    }

    transform.rotation = Quaternion.Slerp(camera.transform.rotation, target, Time.time *rotationSpeed);

}

1 个答案:

答案 0 :(得分:1)

这是因为Rigidbody.AddForce采用世界空间矢量,但是你给它一个局部空间矢量。使用Transform.TransformDirection将您的矢量从本地空间转换为世界空间。

Vector3 force = transform.TransformDirection(0, 0, pitch);
camera.rigidbody.AddForce(force);