I am creating a 3D game in Unity, and I have a script that lets the player look around with the mouse. For moving the player in the direction they are looking, I am using transform.forward. My problem is that when they are looking at the ceiling and press 'W' (forward), they begin rising into the air. Basically I need to know if there is a method or a sub-method of transform.forward
that allows movement on only the x and z axes.
Here is my movement script (C#):
if (transform.rotation.x < -10)
{
//do no forward or backward movement
Debug.Log("Rotation too great to forward move...");
tooGoodForMovement = true;
}
else
{
tooGoodForMovement = false;
if (Input.GetKey(KeyCode.W))
{
//Forward
player.velocity = (transform.FindChild("Main Camera").transform.forward * moveSpeed);
}
if (Input.GetKey(KeyCode.S))
{
//Back
player.velocity = (-transform.FindChild("Main Camera").transform.forward * moveSpeed);
}
}
if (Input.GetKey(KeyCode.A))
{
//Left
player.velocity = -transform.FindChild("Main Camera").transform.right * moveSpeed;
}
if (Input.GetKey(KeyCode.D))
{
//Right
player.velocity = transform.FindChild("Main Camera").transform.right * moveSpeed;
}