is_on_floor() not working properly

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

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.

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

Ertain | 2020-06-19 13:37

Do you have a floor at all?

MaaaxiKing | 2020-06-19 14:44

Yes, it’s a StaticBody2D with CollisionShape2D

zeromaintenance | 2020-06-19 18:56

:bust_in_silhouette: Reply From: zeromaintenance

vector = move_and_slide(vector) solved it.

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.

Ertain | 2020-06-19 20:20

:bust_in_silhouette: Reply From: RemyIsCool

The second argument of move_and_slide(vector) should be Vector2.UP because that signifies the up direction.

Omg Thank you!!!

EnderMaster08 | 2023-02-13 05:14