Attention | Topic was automatically imported from the old Question2Answer platform. | |
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:
apply_gravity(delta)
jump()
move()
animate()
move_and_slide(velocity, UP)
func apply_gravity(delta : float) -> void:
if is_on_floor():
velocity.y = 0
else:
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
else:
velocity.x = 0.0
How can I fix this?