In my game you can move around with WASD and use space bar to jump. Whenever I jump, the character follows my mouse rather than simply jumping in the direction the player intended. Currently, I am able to jump forwards or sideways and simply use my mouse to do 360 spins until my player reaches the ground which should not be possible.
What is supposed to happen is, you can still look around slightly as you are jumping, but the character should only jump in the direction the player wants with their key input and that’s it. So if I am running with shift+W and I press space bar, my character should jump forward and I should not be able to use my mouse to move the player around while the jump is happening.
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float walkSpeed = 12f;
public float sprintSpeed = 26f;
public float gravity = -9.81f;
public float jumpHeight = 2.6f;
public float groundDistance = 0.6f;
public LayerMask groundMask;
Vector3 velocity;
public bool isGrounded;
float x, z;
public void Update()
{
isGrounded = controller.isGrounded;
if (isGrounded)
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
}
Vector3 move = transform.right * x + transform.forward * z; // Player movement
if (move.magnitude > 1)
move /= move.magnitude;
if (isGrounded)
{
if (Input.GetKey(KeyCode.LeftShift))
{
speed = sprintSpeed;
}
else
{
speed = walkSpeed;
}
}
if (Input.GetButtonDown("Jump") && isGrounded) // Jumping
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (!isGrounded)
{
}
velocity.y += gravity * Time.deltaTime;
controller.Move(move * speed * Time.deltaTime);
controller.Move(velocity * Time.deltaTime);
}
}
I have tried Vector3.up with transform forward and then included a FixedUpdate with vector3.down but my game gets all buggy and I’ve tried altering the code but it makes it a lot more jittery. I’ve tried using Unity docs aswell but no success so far.