Hello i have a problem. When i press W the object jumps up but each time with a different height. I tried to do it through fixedupdate, but then he either jumps every time with a different height or does not jump at all.
void Update()
{
Jump();
}
private void Jump()
{
if (Input.GetKeyDown(KeyCode.W))
{
var jumpVel = new Vector2(0, jumpForce * Time.deltaTime);
rb.velocity += jumpVel;
}
}
You’re basically scaling your jumping force erratically.
Constant forces/motions (i.e. velocity) never need to be scaled by the framerate. That’s what you do when you’re making that change yourself.
// When you first change this, expect it to be ~60+ times
// stronger than you intend, depending on your average framerate
Vector2 jumpVel = new Vector2(0, jumpForce);
Something like this should do it.
private bool bJumping = false;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W) && !bJumping)
{
bJumping = true;
Jump();
} else bJumping = false; //now jumping is possible again
//issue: you need to keep it true until you land (or jumping in the air is possible)
}
private void Jump()
{
var jumpVel = new Vector2(0, jumpForce * Time.fixedDeltaTime);
rb.velocity += jumpVel;
}