Advertisement
Zunesha

Script de Movimentação em Grid sem diagonal e com colisão perfeita usando raycast

Sep 8th, 2024 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.25 KB | Source Code | 0 0
  1. Script de Movimentação em Grid sem diagonal e com colisão perfeita usando raycast
  2.  
  3. extends CharacterBody2D
  4.  
  5. var grid_size = 128
  6. var direction = Vector2.ZERO
  7.  
  8. @onready var wall_detector: RayCast2D = $RayCast2D
  9.  
  10. func _ready() -> void:
  11.     global_position = Vector2(192,192)
  12.  
  13. func _input(event):
  14.     if event is InputEventKey and event.is_action_pressed("ui_right") or event.is_action_pressed("ui_left") or event.is_action_pressed("ui_up") or event.is_action_pressed("ui_down"): #antes era #.pressed:
  15.         move_player()
  16.  
  17. func move_player():
  18.     direction = Input.get_vector("ui_left","ui_right","ui_up","ui_down")
  19.  
  20.     # Proibir movimentação diagonal
  21.     if abs(direction.x) > 0 and abs(direction.y) > 0:
  22.         direction = Vector2.ZERO
  23.    
  24.     if direction != Vector2.ZERO:
  25.         # Calcular a nova posição
  26.         var new_position = position + direction * grid_size
  27.  
  28.         # Atualizar o RayCast2D com base na nova posição
  29.         if direction.x != 0:
  30.             wall_detector.target_position = Vector2(direction.x * grid_size, 0)
  31.         elif direction.y != 0:
  32.             wall_detector.target_position = Vector2(0, direction.y * grid_size)
  33.  
  34.         wall_detector.force_raycast_update()
  35.  
  36.         if !wall_detector.is_colliding():
  37.             # Aplicar a nova posição se não houver colisão
  38.             position = new_position
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement