Player.gd 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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("ui_left") and !rayLeft.is_colliding():
  43. dire_delta = -1
  44. elif Input.is_action_just_pressed("ui_right") and !rayRight.is_colliding():
  45. dire_delta = 1
  46. if is_moving:
  47. return
  48. grid.set_cell(posix - dirx, posiy - diry, 1)
  49. dire += dire_delta
  50. if dire_delta == -1:
  51. tween.rotate_char(self, rotation_degrees - 90)
  52. if dire < 0:
  53. dire = 3
  54. elif dire_delta == 1:
  55. tween.rotate_char(self, rotation_degrees + 90)
  56. if dire > 3:
  57. dire = 0
  58. turn(dire)
  59. dire_delta = 0
  60. posix += dirx
  61. posiy += diry
  62. target_pos = Vector2(posix * cell_size + cell_half_size, posiy * cell_size + cell_half_size)
  63. tween.move_char(self, target_pos)
  64. is_moving = true
  65. tween.start()
  66. func _on_tween_completed(o, k):
  67. is_moving = false
  68. func _on_crash(b):
  69. alive = false
  70. grid.set_cell(posix - dirx, posiy - diry, 1)
  71. grid.set_cell(posix, posiy, 2)
  72. func turn(dir:int):
  73. dirx = 0
  74. diry = 0
  75. if dir == DIR_UP:
  76. diry -= 1
  77. elif dir == DIR_RIGHT:
  78. dirx += 1
  79. elif dir == DIR_DOWN:
  80. diry += 1
  81. else:
  82. dirx -= 1