Player.gd 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. extends Area2D
  2. # Nodes
  3. export (NodePath) var gridNode
  4. var grid:TileMap
  5. var tween
  6. var rayFront
  7. var rayLeft
  8. var rayRight
  9. # Misc
  10. var cell_size
  11. var cell_half_size
  12. # Enum
  13. const DIR_UP = 0
  14. const DIR_RIGHT = 1
  15. const DIR_DOWN = 2
  16. const DIR_LEFT = 3
  17. # Movement
  18. var posix
  19. var posiy
  20. var dirx = 0
  21. var diry = 0
  22. export var dire = DIR_UP
  23. var dire_delta = 0
  24. var is_moving = false
  25. var target_pos
  26. func _ready():
  27. grid = get_node(gridNode)
  28. cell_size = int (grid.get_cell_size().x)
  29. cell_half_size = cell_size / 2
  30. posix = int (position.x / 64)
  31. posiy = int (position.y / 64)
  32. turn(dire)
  33. tween = $Tween
  34. tween.connect_into(self)
  35. rayFront = $RayFront
  36. rayLeft = $RayLeft
  37. rayRight = $RayRight
  38. func _physics_process(delta):
  39. if Input.is_action_just_pressed("ui_left"):
  40. dire_delta = -1
  41. elif Input.is_action_just_pressed("ui_right"):
  42. dire_delta = 1
  43. if is_moving:
  44. return
  45. dire += dire_delta
  46. if dire_delta == -1:
  47. tween.rotate_char(self, rotation_degrees - 90)
  48. if dire < 0:
  49. dire = 3
  50. elif dire_delta == 1:
  51. tween.rotate_char(self, rotation_degrees + 90)
  52. if dire > 3:
  53. dire = 0
  54. turn(dire)
  55. dire_delta = 0
  56. posix += dirx
  57. posiy += diry
  58. target_pos = Vector2(posix * cell_size + cell_half_size, posiy * cell_size + cell_half_size)
  59. tween.move_char(self, target_pos)
  60. is_moving = true
  61. tween.start()
  62. func _on_tween_completed(o, k):
  63. is_moving = false
  64. func turn(dir:int):
  65. dirx = 0
  66. diry = 0
  67. if dir == DIR_UP:
  68. diry -= 1
  69. elif dir == DIR_RIGHT:
  70. dirx += 1
  71. elif dir == DIR_DOWN:
  72. diry += 1
  73. else:
  74. dirx -= 1