0 votes

I'm very new to Godot and I'm trying to create a simple 2D platformer. My problem is how to implement jumping. I have to check if the character is on the floor otherwise the player can just spam space bar to fly. Luckily, KinematicBody2D has is_on_floor() function perfect for this purpose.

Here's my script:

extends KinematicBody2D

var walk_speed = 350
var gravity = 700

var vector = Vector2()

func get_input():
    vector = Vector2()
    if Input.is_action_pressed("move_forward"):
        vector.x += 1
    if Input.is_action_pressed("move_backward"):
        vector.x -= 1

    vector = vector.normalized() * walk_speed

func _physics_process(_delta):
    vector.y = gravity

No matter where my character is, is_on_floor() always returns False. Documentation says is_on_floor() updates when calling move_and_slide(), I am calling it after move_and_slide() and it still doesn't work.

asked Jun 19 in Engine by zeromaintenance (19 points)

Hmm, maybe you have to assign move_and_slide() back to vector? Change the code to vector = move_and_slide(vector)?

Do you have a floor at all?

Yes, it's a StaticBody2D with CollisionShape2D

1 Answer

0 votes
Best answer

vector = move_and_slide(vector) solved it.

answered Jun 19 by zeromaintenance (19 points)

That one's a bit of a gotcha. The is_on_floor() function is updated after move_and_slide(), and so I guess the code needs the vector variable at the top of the _physics_process() function.

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.