Godot Version
Godot V4.3
Question
Good afternoon, I’m new here, and new to programming, I work with 2D design, pixel art and I decided to try to do something with Godot, anyway
I would like my character to climb the stairs, but when he passes the stairs the idle and run animations stop, I would also like him to enter the stairs just from the floor, and not by jumping, thanks in advance!
My code:
extends CharacterBody2D
const SPEED = 100.0
const JUMP_VELOCITY = -200.0
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
var on_ladder := false
var is_climbing := false # Nova variável para controlar se está subindo/descendo
var climb_speed: float = 50.0 # Velocidade de subida/descida
var gravity: float = 800.0 # Força da gravidade
func _physics_process(delta: float) → void:
# Aplicar gravidade apenas se não estiver na escada
if not is_on_floor() and not is_climbing:
velocity.y += gravity * delta
# Pular apenas se não estiver na escada e estiver no chão
if Input.is_action_just_pressed("jump") and is_on_floor() and not is_climbing:
velocity.y = JUMP_VELOCITY
# Movimento horizontal apenas se não estiver escalando
var direction := 0.0
if not is_climbing:
direction = Input.get_axis("move_left", "move_right")
# Flipar o sprite apenas se não estiver escalando
if not is_climbing:
if direction > 0:
animated_sprite.flip_h = false
elif direction < 0:
animated_sprite.flip_h = true
# Animação de subir e descer a escada
if on_ladder:
if Input.is_action_pressed("climb"):
velocity.y = -climb_speed # Subir
animated_sprite.play("climb")
is_climbing = true
elif Input.is_action_pressed("down"):
velocity.y = climb_speed # Descer
animated_sprite.play("climb")
is_climbing = true
else:
velocity.y = 0 # Parar de subir/descer
is_climbing = false
animated_sprite.stop()
else:
is_climbing = false # Fora da escada, não está escalando
# Animação de andar, pular e cair
if not is_climbing:
if is_on_floor():
if direction == 0:
animated_sprite.play("idle")
else:
animated_sprite.play("run")
else:
if velocity.y < 0:
animated_sprite.play("jump")
else:
animated_sprite.play("fall")
# Aplicar movimento horizontal apenas se não estiver escalando
if not is_climbing:
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
else:
velocity.x = 0 # Parar o movimento horizontal na escada
move_and_slide()
func _on_ladder_checker_body_entered(body: Node2D) → void:
on_ladder = true
func _on_ladder_checker_body_exited(body: Node2D) → void:
on_ladder = false
is_climbing = false # Saiu da escada, não está mais escalando