简体   繁体   English

Unity相机旋转

[英]Unity camera rotation

I have a camera in my scene I am controlling with a third party device. 我在用第三方设备控制的场景中有一个摄像头。 If I spin the device, pitch it forward etc the same action is replicated with my camera. 如果我旋转设备,将其向前倾斜等,相机将复制相同的动作。 However, I'm stuck working out how to always make sure my camera is facing forward and moving forward in spite of its Y rotation. 但是,我一直在努力研究如何始终确保我的相机在Y轴旋转的情况下仍面向前方并向前移动。

For example, my camera starts at point 0,0,0 with the same rotation value. 例如,我的相机从具有相同旋转值的点0,0,0开始。 If I rotate my camera 90 degrees (either side) and move my camera forward, my view now moves side ways. 如果我将相机旋转90度(左右)并向前移动相机,则视图现在会向侧面移动。 How can I get it so that where ever my camera is facing, that is my forward direction? 如何获得它,以便相机面对的任何地方,即我的前进方向?

Here is my code so far: 到目前为止,这是我的代码:

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);

}

This occurs because Rigidbody.AddForce takes a world space vector, but you are giving it a local space vector. 发生这种情况是因为Rigidbody.AddForce接受了一个世界空间矢量,但是您Rigidbody.AddForce了它一个局部空间矢量。 Use Transform.TransformDirection to convert your vector from local space to world space. 使用Transform.TransformDirection将向量从局部空间转换为世界空间。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM