Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends CharacterBody2D
- const TILE_SIZE = 16
- @onready var ray = $RayCast
- @onready var animation_tree = $AnimationTree
- @onready var animation_state = animation_tree["parameters/playback"] as AnimationNodeStateMachinePlayback
- const DIRECTIONS = {
- "right": Vector2(1, 0),
- "left": Vector2(-1, 0),
- "down": Vector2(0, 1),
- "up": Vector2(0, -1)
- }
- var direction_history = []
- var input_direction = Vector2.ZERO
- var initial_position = Vector2.ZERO
- var is_moving = false
- var is_running = false
- var percent_moved_to_next_tile = 0.0
- @export var walk_speed = 4.0
- @export var run_speed = 8.0
- @export var can_move : bool = true
- func _ready():
- initial_position = position
- func _physics_process(delta):
- process_player_input()
- if is_moving and can_move:
- move(delta)
- update_animation(input_direction, true)
- else:
- update_animation(input_direction, false)
- func process_player_input():
- for direction in DIRECTIONS.keys():
- if Input.is_action_just_pressed(direction):
- direction_history.append(direction)
- elif Input.is_action_just_released(direction):
- direction_history.erase(direction)
- input_direction = Vector2.ZERO
- if direction_history.size() > 0:
- var last_direction = direction_history[direction_history.size() - 1]
- input_direction = DIRECTIONS[last_direction]
- is_running = Input.is_action_pressed("run")
- initial_position = position
- ray.target_position = input_direction * TILE_SIZE
- ray.force_raycast_update()
- if not ray.is_colliding():
- is_moving = true
- else:
- input_direction = Vector2.ZERO
- is_moving = false
- func move(delta):
- var speed = is_running ? run_speed : walk_speed
- percent_moved_to_next_tile += speed * delta
- 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
- direction_history.clear() # Limpa o histórico após mover um tile
- else:
- position = initial_position + (TILE_SIZE * input_direction * percent_moved_to_next_tile)
- 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")
- animation_tree.set("parameters/Walk/blend_position", direction)
- else:
- animation_state.travel("idle")
- animation_tree.set("parameters/idle/blend_position", direction)
Advertisement
Add Comment
Please, Sign In to add comment