Guest User

Untitled

a guest
Dec 16th, 2023
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. extends CharacterBody2D
  2.  
  3. const TILE_SIZE = 16
  4. @onready var ray = $RayCast
  5. @onready var animation_tree = $AnimationTree
  6. @onready var animation_state = animation_tree["parameters/playback"] as AnimationNodeStateMachinePlayback
  7.  
  8. const DIRECTIONS = {
  9. "right": Vector2(1, 0),
  10. "left": Vector2(-1, 0),
  11. "down": Vector2(0, 1),
  12. "up": Vector2(0, -1)
  13. }
  14.  
  15. var direction_history = []
  16. var input_direction = Vector2.ZERO
  17. var initial_position = Vector2.ZERO
  18. var is_moving = false
  19. var is_running = false
  20. var percent_moved_to_next_tile = 0.0
  21. @export var walk_speed = 4.0
  22. @export var run_speed = 8.0
  23. @export var can_move : bool = true
  24.  
  25. func _ready():
  26. initial_position = position
  27.  
  28. func _physics_process(delta):
  29. process_player_input()
  30. if is_moving and can_move:
  31. move(delta)
  32. update_animation(input_direction, true)
  33. else:
  34. update_animation(input_direction, false)
  35.  
  36. func process_player_input():
  37. for direction in DIRECTIONS.keys():
  38. if Input.is_action_just_pressed(direction):
  39. direction_history.append(direction)
  40. elif Input.is_action_just_released(direction):
  41. direction_history.erase(direction)
  42.  
  43. input_direction = Vector2.ZERO
  44. if direction_history.size() > 0:
  45. var last_direction = direction_history[direction_history.size() - 1]
  46. input_direction = DIRECTIONS[last_direction]
  47.  
  48. is_running = Input.is_action_pressed("run")
  49. initial_position = position
  50. ray.target_position = input_direction * TILE_SIZE
  51. ray.force_raycast_update()
  52. if not ray.is_colliding():
  53. is_moving = true
  54. else:
  55. input_direction = Vector2.ZERO
  56. is_moving = false
  57.  
  58. func move(delta):
  59. var speed = is_running ? run_speed : walk_speed
  60. percent_moved_to_next_tile += speed * delta
  61. if percent_moved_to_next_tile >= 1.0:
  62. position = initial_position + (TILE_SIZE * input_direction)
  63. percent_moved_to_next_tile = 0.0
  64. is_moving = false
  65. direction_history.clear() # Limpa o histórico após mover um tile
  66. else:
  67. position = initial_position + (TILE_SIZE * input_direction * percent_moved_to_next_tile)
  68.  
  69. func update_animation(direction, is_moving):
  70. if is_running and is_moving:
  71. animation_state.travel("run")
  72. animation_tree.set("parameters/run/blend_position", direction)
  73. elif is_moving:
  74. animation_state.travel("Walk")
  75. animation_tree.set("parameters/Walk/blend_position", direction)
  76. else:
  77. animation_state.travel("idle")
  78. animation_tree.set("parameters/idle/blend_position", direction)
Advertisement
Add Comment
Please, Sign In to add comment