Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Player starts flying after a few jump clicks

Hello! I've started making a really simple 2D game. I'm trying to make a player move and jump. The movement on my player is fine, but the jumping is really odd. If I hold the space button down or tap if a few times rapidly, the player starts flying and never stops. I'm using a bool (grounded) to stop double jumping.

This is the code:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class PlayerMovement : MonoBehaviour


  public float moveSpeed = 5;

  public float jumpForce;

  public bool grounded;

  private Rigidbody2D rb;

  private float move;

  // Start is called before the first frame update

  void Start()


    bool grounded = false;

    rb = GetComponent<Rigidbody2D>();


  private void OnCollisionEnter2D(Collision2D collision)


    grounded = true;


  private void OnCollisionExit2D(Collision2D collision)


    grounded = false;


  // Update is called once per frame

  void Update()


    move = Input.GetAxisRaw("Horizontal");

    rb.AddForce(new Vector2(move * moveSpeed, rb.velocity.y));

    if (Input.GetKeyDown(KeyCode.Space) && grounded == true)


      rb.AddForce(new Vector3(rb.velocity.x, jumpForce, rb.velocity.y));




Best Answers

  • Accepted Answer

    Update runs every frame update and is essentially equal to fps so for a 2d game this is probably over 200. On Collison runs once every physics update which is 50 times by default. this offset can cause weird things to happen sometimes. In addition to this using a Collision to determine f you are grounded is not the best system because if you were on the side of a wall or touching a roof that would count as grounded. as well. In my experience the best method for a ground check is using a ray cast and checking the distance to the ground. This eliminates the wall/roof problem and also eliminates weird behavior usually. Another advantage with this approach is you can use layer masks with it.

    Another easy approach I have found is adding a tiny non rendered box to the bottom of a player and giving that a character controller. Then you can use that box to check .Is Grounded.

  • dhanrajdhanraj Member
    Accepted Answer

    Try using FixedUpdate instead of update.

    And Multiply the AddForce Statement with Time.fixedDeltaTime

    Hope that would help :)

Sign In or Register to comment.