- Home /
The player doesn't jump to the left with the W key pressed
For some reason, when I try to jump to the left with W it doesn't work. I implemented the jump and the walk, in 2 separated functions on the player controller, and works fine when I don't press W. And also the jump to the left works fine with any other key pressed.
What happens is if the player was pressing W, he can jump or walk to the left, but not both at the same time. If the player presses W and walks to the left after, the jump doesn't work. If the player presses W and jumps, he can't go to the left in the air. Ironically it works if the player presses W and jumps to the right.
My first thought was the vertical axis because I am using the horizontal axis, but I try to jump to the left with the UP arrow key pressed, and works. The jump to the left also works fine with the S key pressed.
I don't know what is the reason for that, but I don't think this is a problem for my code. I suspected it was a problem with the Unity editor, so I created a build to test, and the result was the same.
The player gameobject has a transform, a dynamic rigidbody2d with 5 of gravity scale, collision detection continuous, freeze rotation on z, a simple box collider 2d, a sprite renderer, and the player controller script.
This is the PlayerController script:
(I set speed 10f and jump 20f in the inspector)
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed;
[SerializeField] private float jump;
private bool canJump = true;
private Rigidbody2D playerRigidbody2D;
private void Start()
{
playerRigidbody2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
Walk();
Jump();
}
private void Walk()
{
float horizontalMovement = Input.GetAxis("Horizontal");
if(horizontalMovement > 0 || horizontalMovement < 0)
{
playerRigidbody2D.velocity = new Vector2(horizontalMovement * speed, playerRigidbody2D.velocity.y);
}
}
private void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
canJump = false;
playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jump);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Ground")
{
canJump = true;
}
}
}
I created a simple project to reproduce this bug, and I put it in Github in the following link: https://github.com/danilomacb/JumpToLeftWithWPressedBug