How to prevent Jumping in the air(pls help I'm stuck at this for weeks now)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By radho

All i want is the character to be able to jump only when he is on the floor i searched and did everything in the internet but it still somehow doesn’t work don’t understand this I copied exactly in every method but still it didn’t work

Heres my code:

var gravity = 9.8
var jump = 5 
var velocity = Vector3(0,0,0)
func _physics_process(delta):

if not is_on_floor():
	velocity.y -= gravity * delta

	if Input.is_action_just_pressed("jump") and is_on_floor(): 
		velocity.y = jump

	
move_and_slide(velocity) 

*when i remove the “and is on floor” argument the jump will work but the problem is you can literally jump in the air

:bust_in_silhouette: Reply From: estebanmolca

If your second IF is nested in the first one, it will only be executed when the first one is true.
In the manual there is an example of how to implement it:

I also recommend reading this to get an idea of how to implement a state machine:
https://gameprogrammingpatterns.com/state.html

:bust_in_silhouette: Reply From: MrEliptik

I see two problems here. Because your indentation is weird, I’m assuming your code is as follows:

func _physics_process(delta):
    if not is_on_floor():
	    velocity.y -= gravity * delta
	    if Input.is_action_just_pressed("jump") and is_on_floor():  
		    velocity.y = jump
    move_and_slide(velocity, Vector3.UP) 

If this is correct, you’ll never reach the part where you jump because as soon as you touch the ground, you can’t go past the first if.

Secondly, for is_on_floor() to work correctly you need two things:

  • Calling move_and_slide() to update its value
  • Provide and UP vector to move_and_slide(). This is needed to know if the body is on the floor, ceiling, or wall. With those correction the code is now:
func _physics_process(delta):
    velocity.y -= gravity * delta

    if Input.is_action_just_pressed("jump") and is_on_floor():  
	    velocity.y = jump

    move_and_slide(velocity, Vector3.UP)