Player.gd 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. var alive = true
  13. # Enum
  14. const DIR_UP = 0
  15. const DIR_RIGHT = 1
  16. const DIR_DOWN = 2
  17. const DIR_LEFT = 3
  18. # Movement
  19. var posix
  20. var posiy
  21. var dirx = 0
  22. var diry = 0
  23. export var dire = DIR_UP
  24. var dire_delta = 0
  25. var is_moving = false
  26. var target_pos
  27. func _ready():
  28. grid = get_node(gridNode)
  29. cell_size = int (grid.get_cell_size().x)
  30. cell_half_size = cell_size / 2
  31. posix = int (position.x / 64)
  32. posiy = int (position.y / 64)
  33. turn(dire)
  34. tween = $Tween
  35. tween.connect_into(self)
  36. rayFront = $RayFront
  37. rayLeft = $RayLeft
  38. rayRight = $RayRight
  39. func _physics_process(delta):
  40. if !alive:
  41. return
  42. if Input.is_action_just_pressed("player_1_turn_left"):
  43. dire_delta = -1
  44. elif Input.is_action_just_pressed("player_1_turn_right"):
  45. dire_delta = 1
  46. if is_moving:
  47. return
  48. grid.set_cell(posix - dirx, posiy - diry, 1)
  49. if dire_delta == -1 and !rayLeft.is_colliding():
  50. tween.rotate_char(self, rotation_degrees - 90)
  51. dire += dire_delta
  52. if dire < 0:
  53. dire = 3
  54. elif dire_delta == 1 and !rayRight.is_colliding():
  55. tween.rotate_char(self, rotation_degrees + 90)
  56. dire += dire_delta
  57. if dire > 3:
  58. dire = 0
  59. turn(dire)
  60. dire_delta = 0
  61. posix += dirx
  62. posiy += diry
  63. target_pos = Vector2(posix * cell_size + cell_half_size, posiy * cell_size + cell_half_size)
  64. tween.move_char(self, target_pos)
  65. is_moving = true
  66. tween.start()
  67. func _on_tween_completed(o, k):
  68. is_moving = false
  69. func _on_crash(b):
  70. alive = false
  71. grid.set_cell(posix - dirx, posiy - diry, 1)
  72. grid.set_cell(posix, posiy, 2)
  73. func turn(dir:int):
  74. dirx = 0
  75. diry = 0
  76. if dir == DIR_UP:
  77. diry -= 1
  78. elif dir == DIR_RIGHT:
  79. dirx += 1
  80. elif dir == DIR_DOWN:
  81. diry += 1
  82. else:
  83. dirx -= 1