Reputation: 2724
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);
}
Upvotes: 0
Views: 1654
Reputation: 1596
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);
Upvotes: 1