Search code examples
c#unity-game-engine2d

Why does the player gameObject continue moving in mid-air, despite no movement keys being pressed? (closed)


I'm making a 2D game in Unity where the player is able to jump and walk left or right. The player should be able to change directions while mid-air, but the problem is that they continue to move in the direction they were moving while jumping, despite no longer pressing the movement key.

Here's the movement script:

public float jumpHeight;

public float speed;

public Rigidbody2D rb;

private bool isGrounded;

public Transform feetPos;

public float checkRadius;

public LayerMask Ground;

private float jumpTimeCounter;

public float jumpTime;

private bool isJumping;

void Update()
{
    PausedThisFrame = false;

    isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, Ground);

    if (isGrounded && Input.GetKeyDown(KeyCode.Space))
    {
        isJumping = true;
        jumpTimeCounter = jumpTime;
        rb.velocity = Vector2.up * jumpHeight;
    }
    if (Input.GetKey(KeyCode.Space) && isJumping)
    {
        if (jumpTimeCounter > 0)
        {
            rb.velocity = Vector2.up * jumpHeight;
            jumpTimeCounter -= Time.deltaTime;
        }
        else
        {
            isJumping = false;
        }
    }
    if (Input.GetKeyUp(KeyCode.Space))
    {
        isJumping = false;
    }
}

void FixedUpdate()
{
    if (Input.GetKey(KeyCode.A))
    {
        Debug.Log("A");
        rb.velocity = new Vector2(-1 * speed, rb.velocity.y);
        transform.eulerAngles = new Vector3(0, 180, 0);
    }
    if (Input.GetKey(KeyCode.D))
    {
        Debug.Log("D");
        rb.velocity = new Vector2(1 * speed, rb.velocity.y);
        transform.eulerAngles = new Vector3(0, 0, 0);
    }
    else
    {
        rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y);
    }
}

I tried debugging the code to see if the script thinks the keys are being pressed but even the script knows that they aren't so i trully have no idea what's changing the velocity of the rigidbody.


Solution

  • The else part of your FixedUpdate() routine seems to be the problem. The part

    else
    {
    rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y);
    }
    

    only assign a copy of the velocity vector to itself. So, the values do not change. Try this one instead of the else

    if (!Input.GetKey(KeyCode.A) &&
        !Input.GetKey(KeyCode.D))
        {
           rb.velocity = new Vector2(0, rb.velocity.y);
        }
    

    The input check is necessary to only set the x-velocity to zero, when no key is pressed ;)