- Home /
my jump key works about once every 10 presses
Basically I have a problem, which is that I have a presumably working jump script, but when I try to jump it has a 10% chance to actually jump (around 10%, it's very random, sometimes it works twice in a row)
I don't want it to be forced to only jump when it's on the ground yet, I just want it to jump consistently.
My unity scene looks like this:
the green square is my player:
rigidbody, frozen Z rotation
box collider, nothing changed
script "PlayerScript" with a public Rigidbody2D variable, containing the Player gameobject's rigidbody2D via the unity inspector.
the white rectangle is the ground:
box collider, nothing changed
here's the PlayerScript script (which is essentially just a jump):
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public Rigidbody2D rb;
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * 10f;
}
}
}
This is all I've done after creating a new unity 2D project. And yet, the jump key does't work about 90% of the time.
My guess is that it has to do with how my unity is set up at the moment, and that there's nothing wrong with the code. Thank you for taking the time to help me, I appreciate you very much! :)
EDIT: after changing FixedUpdate() to Update() it seems to work correctly, although I'm not sure if it's a good idea in the long term. Feedback is still greatly appreciated, even though the problem I had is technically fixed for now.
Answer by gipsnichmeer · Nov 19, 2021 at 07:21 PM
Yes, you should collect user input in Update() since Unity takes input from the operating system every frame. However frames don't always have the same time between them. That's why you should use FixedUpdate() to move things (or generally do things that should constantly have the same speed) A good solution would be to get your input in Update() and then perform the action in FixedUpdate() like this:
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public Rigidbody2D rb;
private bool isSpacePressed = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
isSpacePressed = true;
}
}
void FixedUpdate()
{
if(isSpacePressed)
rb.velocity = Vector2.up * 10f;
}
}
It all makes sense now! Thank you so much for the answer! :)
Happy to help. By the way, you could also do everything inside of Update() but then multiply your velocity with Time.deltaTime (the time in seconds that passed since the last frame)
There are usages for taking the Input in FixedUpdate as well, if you do it right. For example if you want to replay your moves.