0
\$\begingroup\$

I am using the following code for moving a capsule:

Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);

I am using the following code for the camera, which is a child of the capsule. (xRotation is intialized to 0.0f, and playerBody is a transform):

        float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

The character is always moving in the same direction, ignoring the rotation. How can I fix this?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I'm not quite sure what you mean by "ignoring the rotation". However, I'm going to assume this is based off Brackey's FPS movement tutorial, as I have the same code in one of my older projects, and that you are trying to achieve the same thing as the tutorial. In that case, you need to change Vector3 move to

float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;

I'm fairly sure that you can also do this

Vector3 move = transform.right * Input.GetAxis("Horizontal") + transform.forward * Input.GetAxis("Vertical");

and have the code work

The reason your code is not working is because Vector move will move to the player to a world position, which means it will ignore rotation.

By changing the code to this, the direction of the x and z values will be aligned to the player's x and z axis, meaning that if the player rotates, the axis will rotate as well.

I'm far from an experienced programer, but I hope I explained it well enough.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you very much. \$\endgroup\$
    – rohan
    Commented Dec 7, 2020 at 2:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .