0

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.

For example, my camera starts at point 0,0,0 with the same rotation value. If I rotate my camera 90 degrees (either side) and move my camera forward, my view now moves side ways. 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);

}

1 Answer 1

1

This occurs because Rigidbody.AddForce takes a world space vector, but you are giving it a local space vector. Use Transform.TransformDirection to convert your vector from local space to world space.

Vector3 force = transform.TransformDirection(0, 0, pitch);
camera.rigidbody.AddForce(force);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.