Hello all and sorry if the question is too basic.
I'm trying to create a basic jump. The point is that it works fine when y press jump + lateral mov, but it goes to the top and beyond when I press just the jump button. Here is the code. I'd appreciate any help:
BTW: Code is for 2D and in Godot 4.0
const GRAVITY = 10
const JUMP_FORCE = 100.0
var time_gravity = 0
var screen_size # Size of the game window.
var velocity # the area's velocity
var is_on_floor = true
func _ready():
screen_size = get_viewport_rect().size
var pos = Vector2(init_pos_x,init_pos_y)
start(pos)
func _process(delta):
if is_on_floor:
velocity = Vector2.ZERO # Set the player's movement vector to (0,0)
if Input.is_action_pressed("move_right"):
velocity.x += 1
if Input.is_action_pressed("move_left"):
velocity.x -= 1
if Input.is_action_just_pressed("jump"):
if is_on_floor:
is_on_floor = false
velocity.y = (-1) * JUMP_FORCE
if !is_on_floor:
if position.y > init_pos_y:
is_on_floor = true
velocity.y = 0
position.y = init_pos_y
time_on_jump = 0
else:
time_on_jump += delta
velocity.y += GRAVITY * time_on_jump
if velocity.length() > 0:
velocity = velocity.normalized() * move_speed
$AnimatedSprite2D.flip_h = velocity.x < 0
$AnimatedSprite2D.play("run")
else:
$AnimatedSprite2D.play("idle")
position.x += velocity.x * delta
position.y += velocity.y * delta
print_debug("Position: ", position, " Delta: ", delta)
position.x = clamp(position.x, 0, screen_size.x)
position.y = clamp(position.y, 0, screen_size.y)