0 votes

Hi, I coded a 2D character (kinematicbody2d) that can move and jump. In order to jump isonfloor 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?

asked Jan 12 in Engine by calvar (23 points)

1 Answer

+3 votes
Best answer

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)
answered Jan 12 by kidscancode (17,772 points)
selected Jan 14 by calvar

Now it works, Thank you!!

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.