0 votes

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

Godot version 3.2.3
in Engine by (12 points)

2 Answers

0 votes

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:
https://docs.godotengine.org/en/latest/tutorials/physics/using_kinematic_body_2d.html#platformer-movement

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

by (2,096 points)
0 votes

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)
by (621 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.