Unity Jump Error

Hey! I’m learning unity but i have a problem. My jump function is not working properly. Not stable at all. I can jump when i play game but then, i cant jump some times. Sorry for my bad English :frowning:

the codes I use are here:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playercontroller : MonoBehaviour
{
public int speed;
public int jumpSpeed;

Animator animator;
Rigidbody2D rb;

bool canJump = true;
bool faceRight = true;

private void Start()
{
animator = GetComponent();
rb = GetComponent();
}

private void FixedUpdate()
{
float moveInput = Input.GetAxis(“Horizontal”);
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

if(moveInput > 0 || moveInput < 0)
{
animator.SetBool(“isRunning”, true);
}
else
{
animator.SetBool(“isRunning”, false);

}

if (faceRight == true && moveInput < 0)
{
Flip();
}else if(faceRight == false && moveInput > 0)
{
Flip();
}

if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}

private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.transform.tag == “Platform”)
{
canJump = true;
}
}
private void Jump()
{
if (canJump)
{
rb.AddForce(Vector2.up * jumpSpeed);
canJump = false;
}
}

private void Flip()
{
faceRight = !faceRight;
Vector3 scaler = transform.localScale;
scaler.x *= -1;
transform.localScale = scaler;
}

}

Using Input.GetKeyDown inside FixedUpdate is not a good idea, and you’re seeing why. FixedUpdate does not run every frame. By default it only runs 50 times per second, which is slower than the usual framerate of 60+. That means there are frames during which you may have pressed the Spacebar but there was no FixedUpdate call that frame, so you missed the GetKeyDown event.

To get around this it is best practice to do your input handling in Update(), store the user’s intent in a variable then consume the user’s intent in FixedUpdate. Update runs every frame and will never miss input.

1 Like

yeah it worked thanks a lot