I have simple movement set up with a sphere object using a Mouse Orbit style camera and Rigidbody.AddForce(). The main issue is that I want it to move in the direction the camera is facing but only receiving input force along the XZ plane, but when I add force when the camera is facing up or down, I fly up into the air. I understand what is causing this, but I am wondering if there is a way to calculate its XZ rotation in relation to the world space that doesn't involve what I used as a workaround: I attached an empty gameobject as a child to the main camera that the camera movement script doesn't send it the Y rotation.
This is my code prior to me implementing my workaround fix:
function FixedUpdate()
{
var cameraRight : Vector3 = Camera.main.transform.TransformDirection(Vector3.right);
var cameraFront : Vector3 = Camera.main.transform.TransformDirection(Vector3.forward);
cameraRight.Normalize();
cameraFront.Normalize();
if(Input.GetAxis("Horizontal") > 0)
{
Debug.Log("Right");
GetComponent(Rigidbody).AddForce(cameraRight * moveSpeed * Time.deltaTime);
}
if(Input.GetAxis("Horizontal") < 0)
{
Debug.Log("Left");
GetComponent(Rigidbody).AddForce(-cameraRight * moveSpeed * Time.deltaTime);
}
if(Input.GetAxis("Vertical") > 0)
{
Debug.Log("Forward");
GetComponent(Rigidbody).AddForce(cameraFront * moveSpeed * Time.deltaTime);
}
if(Input.GetAxis("Vertical") < 0)
{
Debug.Log("Back");
GetComponent(Rigidbody).AddForce(-cameraFront * moveSpeed * Time.deltaTime);
}
}
I clearly understand why this doesn't work, but I am at a loss as to how to calculate a way to get 100% of the force to be applied forward and backward along the XZ plane whenever the camera's Y rotation isn't perfectly zero.
Any help is much appreciated. Thanks!
↧