Player.gd 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. extends Area2D
  2. # Nodes
  3. var grid:TileMap
  4. var tween
  5. var rayFront
  6. var rayLeft
  7. var rayRight
  8. # Misc
  9. var cell_size
  10. var cell_half_size
  11. var alive = true
  12. # Enum
  13. enum Direction {
  14. UP = 0
  15. RIGHT = 1
  16. DOWN = 2
  17. LEFT = 3
  18. }
  19. # Movement
  20. var posix
  21. var posiy
  22. var dirx = 0
  23. var diry = 0
  24. export var dire = Direction.UP
  25. var dire_delta = 0
  26. var is_moving = false
  27. var target_pos
  28. # Controls
  29. export var turn_left_action:String
  30. export var turn_right_action:String
  31. func _ready():
  32. assert(grid)
  33. assert(turn_left_action)
  34. assert(turn_right_action)
  35. cell_size = int (grid.get_cell_size().x)
  36. cell_half_size = cell_size / 2
  37. posix = int (position.x / 64)
  38. posiy = int (position.y / 64)
  39. turn(dire)
  40. tween = $Tween
  41. tween.connect_into(self)
  42. rayFront = $RayFront
  43. rayLeft = $RayLeft
  44. rayRight = $RayRight
  45. func _physics_process(delta):
  46. if !alive:
  47. return
  48. if Input.is_action_just_pressed(turn_left_action):
  49. dire_delta = -1
  50. elif Input.is_action_just_pressed(turn_right_action):
  51. dire_delta = 1
  52. if is_moving:
  53. return
  54. grid.set_cell(posix - dirx, posiy - diry, 1)
  55. if dire_delta == -1 and !rayLeft.is_colliding():
  56. tween.rotate_char(self, rotation_degrees - 90)
  57. dire += dire_delta
  58. if dire < 0:
  59. dire = 3
  60. elif dire_delta == 1 and !rayRight.is_colliding():
  61. tween.rotate_char(self, rotation_degrees + 90)
  62. dire += dire_delta
  63. if dire > 3:
  64. dire = 0
  65. turn(dire)
  66. dire_delta = 0
  67. posix += dirx
  68. posiy += diry
  69. target_pos = Vector2(posix * cell_size + cell_half_size, posiy * cell_size + cell_half_size)
  70. tween.move_char(self, target_pos)
  71. is_moving = true
  72. tween.start()
  73. func _on_tween_completed(o, k):
  74. is_moving = false
  75. func _on_crash(b):
  76. alive = false
  77. grid.set_cell(posix - dirx, posiy - diry, 1)
  78. grid.set_cell(posix, posiy, 2)
  79. func turn(dir:int):
  80. dirx = 0
  81. diry = 0
  82. if dir == Direction.UP:
  83. diry -= 1
  84. elif dir == Direction.RIGHT:
  85. dirx += 1
  86. elif dir == Direction.DOWN:
  87. diry += 1
  88. else:
  89. dirx -= 1
  90. func is_alive():
  91. return alive