is_on_floor switching between true and false

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

Hi, I coded a 2D character (kinematicbody2d) that can move and jump. In order to jump is_on_floor must be true. However, when movin horizontally the value fluctuates and the jump deas not always triggers. Here’s the code:

extends KinematicBody2D

const SPEED : float = 600.0
const JUMP_SPEED : float = 1500.0
const GRAVITY : float = 2500.0
const UP : Vector2 = Vector2.UP

var velocity : Vector2 = Vector2(0,0)

func _physics_process(delta : float) -> void:
	move_and_slide(velocity, UP)

func apply_gravity(delta : float) -> void:
	if is_on_floor():
		velocity.y = 0
		velocity.y += GRAVITY * delta

func jump() -> void:
	print("is_on_floor: ",is_on_floor())
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y -= JUMP_SPEED

func move() -> void:
	if Input.is_action_pressed("left") and not Input.is_action_pressed("right"):
		velocity.x = -SPEED
	elif Input.is_action_pressed("right") and not Input.is_action_pressed("left"):
		velocity.x = SPEED
		velocity.x = 0.0


How can I fix this?

:bust_in_silhouette: Reply From: kidscancode

You must apply gravity constantly. An attempted move into the floor is how move_and_slide() knows to set is_on_floor() to true.

func apply_gravity(delta : float) -> void:
    velocity.y += GRAVITY * delta

Also, you’re discarding the result of move_and_slide() so your y velocity will accumulate infinitely. This is why it returns a resultant vector after the slide:

velocity = move_and_slide(velocity, UP)

Now it works, Thank you!!

calvar | 2020-01-14 22:31