Search Unity

Pressing 2 keys the same time but does not update (2D PlayerController a and d for walk)

Discussion in 'Scripting' started by MindmaxTTV, Apr 17, 2021.

  1. MindmaxTTV

    MindmaxTTV

    Joined:
    Apr 17, 2021
    Posts:
    1
    Hello,
    I'm pretty new to Unity so I watched up videos where people developed a playerController to move the Player around (2D Platformer Walk left|right|jump). So the movement actually works. When I press "a" the player moves left and when i press "d" the player moves right. But when I press "d" first so the player moves right and then press "a" while keep pressing "d", the new key ("a") isn't recognized. When I do the opposite ("a" first than "d") it does recognize the newest key. I watched up a few topics about this issue on the Internet but they call it a bug from Unity.

    Basic Code from the FixedUpdate() Method:
    Code (CSharp):
    1.  void FixedUpdate()
    2.     {
    3.         isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, ground);
    4.  
    5.         if (Input.GetKey("d"))
    6.         {
    7.             rb2d.velocity = new Vector2(runSpeed, rb2d.velocity.y);
    8.         }
    9.         else if (Input.GetKey("a"))
    10.         {
    11.             rb2d.velocity = new Vector2(-runSpeed, rb2d.velocity.y);
    12.         }
    Would be great if you can tell me how to solve this issue! Best regards Max :)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    As long as you're holding D with the code above, the else on line 9 will never fire, so it never even checks for A

    Remove the else, but remember, A will now always win.

    Define what you want to happen when both A and D are pressed. Latest? Neither? First?

    Every one requires a different way of coding.