Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Estende a classe CharacterBody2D para criar um corpo de personagem que pode se mover e colidir
- extends CharacterBody2D
- # Define o tamanho do tile (bloco) no jogo
- const TILE_SIZE = 16
- @onready var ray = $RayCast
- @onready var animation_tree = $AnimationTree
- @onready var animation_state = animation_tree["parameters/playback"] as AnimationNodeStateMachinePlayback
- # Armazena a última direção que o personagem estava se movendo
- var last_direction = Vector2(0, 1)
- # Direção atual do input
- var input_direction = Vector2.ZERO
- # Posição inicial do personagem antes de começar a se mover
- var initial_position = Vector2.ZERO
- # Flag que indica se o personagem está se movendo
- var is_moving = false
- var is_running = false
- # Percentual da movimentação concluída para o próximo tile
- var percent_moved_to_next_tile = 0.0
- @export var walk_speed = 3.0
- @export var run_speed = 8.0
- @export var can_move : bool = true
- func _ready():
- # Define a posição inicial do personagem
- initial_position = position
- func _physics_process(delta):
- # Se o personagem não está se movendo, processa o input do jogador
- if not is_moving:
- process_player_input()
- # Se o personagem está se movendo e pode se mover, atualiza a animação e move o personagem
- if is_moving and can_move:
- last_direction = input_direction
- update_animation(input_direction, true)
- move(delta)
- else:
- # Se o personagem não está se movendo, atualiza a animação para o estado de inatividade
- update_animation(last_direction, false)
- # Função para processar o input do jogador
- func process_player_input():
- # Calcula o input horizontal e vertical
- var horizontal_input = int(Input.get_action_strength("right")) - int(Input.get_action_strength("left"))
- var vertical_input = int(Input.get_action_strength("down")) - int(Input.get_action_strength("up"))
- if Input.is_action_pressed("run"):
- is_running = true
- else:
- is_running = false
- # Determina a direção do input priorizando o eixo com maior intensidade
- if abs(horizontal_input) > abs(vertical_input):
- input_direction = Vector2(horizontal_input, 0)
- elif abs(vertical_input) > abs(horizontal_input):
- input_direction = Vector2(0, vertical_input)
- else:
- # Se nenhum input for detectado, sai da função
- return
- # Atualiza a posição inicial e verifica colisões usando o RayCast
- initial_position = position
- ray.target_position = input_direction * TILE_SIZE
- ray.force_raycast_update()
- if not ray.is_colliding():
- is_moving = true
- else:
- # Se houver uma colisão, reseta a direção do input
- input_direction = Vector2.ZERO
- # Função para mover o personagem
- func move(delta):
- var speed = walk_speed
- if is_running:
- speed = run_speed
- else:
- speed = walk_speed
- # Incrementa o percentual de movimentação baseado na velocidade de caminhada
- percent_moved_to_next_tile += speed * delta
- # Se o personagem se moveu 100% da distância para o próximo tile, atualiza a posição
- if percent_moved_to_next_tile >= 1.0:
- position = initial_position + (TILE_SIZE * input_direction)
- percent_moved_to_next_tile = 0.0
- is_moving = false
- input_direction = Vector2.ZERO # Reseta a direção do input após o movimento
- else:
- # Se ainda não se moveu completamente, atualiza a posição de forma proporcional
- position = initial_position + (TILE_SIZE * input_direction * percent_moved_to_next_tile)
- # Função para atualizar a animação do personagem
- func update_animation(direction, is_moving):
- if is_running and is_moving:
- animation_state.travel("run")
- animation_tree.set("parameters/run/blend_position", (direction))
- elif is_moving:
- animation_state.travel("Walk")
- # Configura a posição de blend da animação de caminhada baseado na direção
- animation_tree.set("parameters/Walk/blend_position", (direction))
- else:
- animation_state.travel("idle")
- # Configura a posição de blend da animação de inatividade baseado na última direção
- animation_tree.set("parameters/idle/blend_position", direction)
Advertisement
Add Comment
Please, Sign In to add comment