Player.gd 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. grid.set_cell( posix, posiy, 1)
  57. posix += dirx
  58. posiy += diry
  59. target_pos = Vector2(posix * cell_size + cell_half_size, posiy * cell_size + cell_half_size)
  60. tween.move_char(self, target_pos)
  61. is_moving = true
  62. tween.start()
  63. func _on_tween_completed(o, k):
  64. is_moving = false
  65. func turn(dir:int):
  66. dirx = 0
  67. diry = 0
  68. if dir == DIR_UP:
  69. diry -= 1
  70. elif dir == DIR_RIGHT:
  71. dirx += 1
  72. elif dir == DIR_DOWN:
  73. diry += 1
  74. else:
  75. dirx -= 1