Home > Software engineering >  Why is my player movement inverted when I turn around?
Why is my player movement inverted when I turn around?

Time:01-11

I used rigidbodies a lot and recently started using character controllers. I have basic movement code for my character controller here:

public void Update()
    {
        isGrounded = controller.isGrounded;
if (isGrounded)
        {
            x = Input.GetAxis("Horizontal");
            z = Input.GetAxis("Vertical");
        }
        Vector3 move = Vector3.forward * z   Vector3.right * x;
        controller.Move(move * speed * Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        if (!isGrounded)
        {
        }

        velocity.y  = gravity * Time.deltaTime; // Gravity for jumps

        controller.Move(velocity * Time.deltaTime);
    }

The reason I am using this code is because I'm trying to make sure that when my player jumps, the jump does not follow my camera around. This code does that, however if I rotate 180 degrees on the y axis, my WASD keys all become inverted. I've tried adding * (1) but that just makes it worse. If I replace Vector3.forward & Vector3.right to transform.forward & transform.right, the keys are no longer inverted but then my jump is controlled by my mouse movement, so I'm really trying to get the first line of code to work.

CodePudding user response:

Vector3.forward is always (1, 0, 0). If you want the movement to be based on the camera's rotation you need to use Transform.forward and Transform.right(Assuming your character only has rotation around the y axis)

If you don't want the jump to be controllable mid-air, you have to logic to create momentum and prevent the player from changing their momentum if they are in the air. The first line is never going to work.

  • Related