KinematicBody2D is changing between is_on_floor and !is_on_floor while running

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

Hey, I have this problem with the state of is_on_floor on my kinematicBody2D while runing/moving only on the x axis. The state is always switching even though the player is not leaviing the ground at all. Any help would be grat :slight_smile:

her is my code:

extends KinematicBody2D

export var velocity = Vector2(0,0)
export var slide = 0.2
const SPEED = 280
const JUMPFORCE = -900
const GRAVITY = 30

var flyJump = true


func _physics_process(delta):
	velocity = move_and_slide(velocity, Vector2.UP)
	velocity.x = lerp(velocity.x,0,slide)
	
	if Input.is_action_pressed("right"):
		velocity.x = SPEED
		$AnimatedSprite.play("run")
		$AnimatedSprite.flip_h = false
	elif Input.is_action_pressed("left"):
		velocity.x = -SPEED
		$AnimatedSprite.play("run")
		$AnimatedSprite.flip_h = true
	else:
		$AnimatedSprite.play("idle")
	
	
	if Input.is_action_just_pressed("jump"):
		if flyJump == true:
			velocity.y = JUMPFORCE

	
	if is_on_floor():
		flyJump = true 

	if !is_on_floor():
		coyoteTime()
		velocity.y += GRAVITY
		print("xxx")
		$AnimatedSprite.play("jump")
	
func coyoteTime():
	yield(get_tree().create_timer(1), "timeout")
	flyJump = false
:bust_in_silhouette: Reply From: kidscancode

In order for is_on_floor() to work properly, you must apply gravity at all times, not just when in the air.

:bust_in_silhouette: Reply From: qez008

You might want to try move_and_slide_with_snap() instead of move_and_slide(). Your issue might be caused by bumps on the ground (there are even tiny gaps between tiles if you are using a tile map). move_and_slide_with_snap() will make sure your kinematic body sticks to the ground.

Note: you have to disabled snap when you want to jump.