Search code examples
c#unity-game-engine2d-gamesgamecontroller

Problem in character control "Character can't jump"


I am practicing with creating a 2D-Game and I write the C#-script code but my character can't jump.

I try to replace "Space" with "UpArrow" that also didn't work.

if (Input.GetKey(KeyCode.UpArrow) && onGround)
 {
 rb.velocity = new Vector2(rb.velocity.x, jumppower);
 }

Nothing Happen. Character can'r move Right and Left but not jump.


Solution

  • Some items to start with:

    1. make sure onGroundis true. => add a Debug.Log($"is on ground {onGround}") before the if and check it.
    2. Make sure the code is in the Update() loop (you can set it also in FixedUpdate, but update is better)

    Then I see a logic issue. This is what happens in your code:

    • you're on the ground
    • you add velocity and move up
    • you're no more on the ground
    • the if fails so vertical velocity stops because you're no more on the ground
    • player falls back

    To solve this replace this line:

    rb.velocity = new Vector2(rb.velocity.x, jumppower);
    

    With this:

    rb.AddForce(new Vector2(0, jumppower), ForceMode2D.Impulse);