Strange behavior of my jump script

Hi, i’m new to unity and trying to write a simple player movement script on my own, with a jump set on space bar that has the basic rules of a video game jump (no jump mid-air, jump during a movement is taken in account…)
Here is what i came up with :
In FixedUpdate :

	if (Input.GetKeyDown("space") && transform.position.y < 0.5f )
		{
			Jump();
			
		} 

         void Jump(){
	rigidBody.AddForce (Vector3.up * jumpHeight);
}

Jump is outside of FixedUpdate of course.
My problem is that sometimes, the player object will only move by a few units and sometimes it’ll make a huge jump. So far i couldn’t find any pattern to understand the logic between the different jumps.

Is there a way to code a more reliable jump, i want to set a height and have my player object do a nice and smooth jump of that height. and if the player is moving during the jump, i want the object to jump in that direction.

Thanks for your help :slight_smile:

Ok, so as for the grounding mechanism use OnCollisionEnter() and OnCollisionExit() to change a boolean for whether the object is grounded or not, and remove the transform.position.y<0.5 . To do this just place a tag on the ground object and change the boolean whenever it collides with the tagged ground.

Try using

rigidBody.velocity = new Vector3(rigidBody.velocity.x, jumpHeight, rigidBody.velocity.z);

That should hopefully resolve your problem.

you should probably use forcemode.impulse or velocity change. Unity - Scripting API: ForceMode

You can probably just avoid all these problems by adding a “Character Controller”, Component on your Player object

Then just add the code from this official Unity script example onto your Player object.

You can edit the fine details on the Component, and the Player movement in the above script example.