0

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;
        }
Sub 6 Resources
  • 1,674
  • 15
  • 31

1 Answers1

2

Try setting your velocity vector into a temporary variable and resetting the Y to zero.

Transform camera;

void Start()
{
    //Cache transform.FindChild so that we don't have to do it every time
    camera = transform.FindChild("Main Camera");
}

Then in your other function:

Vector3 velocity = Vector3.zero;

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
        velocity = camera.forward * moveSpeed;
    }
    if (Input.GetKey(KeyCode.S))
    {
        //Back
        velocity = -camera.forward * moveSpeed;
    }
}
if (Input.GetKey(KeyCode.A))
{
    //Left
    velocity = -camera.right * moveSpeed;
}

if (Input.GetKey(KeyCode.D))
{
    //Right
    velocity = camera.right * moveSpeed;
}

velocity.Y = 0;
player.velocity = velocity;
Abion47
  • 22,211
  • 4
  • 65
  • 88