Track.gd 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. class_name Track
  2. extends Node2D
  3. const TRACK_PIECE = preload("uid://4gxhnql5bjk6")
  4. @export var path := []
  5. var pieces := []
  6. var length := 0
  7. @export_enum("Closed", "Open") var start_point := 0
  8. @export_enum("Closed", "Open") var end_point := 0
  9. @export var invisible := false:
  10. set(value):
  11. invisible = value
  12. update_pieces()
  13. var editing := false
  14. const DIRECTIONS := [
  15. Vector2i(-1, -1), # 0
  16. Vector2i.UP, # 1
  17. Vector2i(1, -1), # 2
  18. Vector2i.RIGHT, # 3
  19. Vector2i(1, 1), # 4
  20. Vector2i.DOWN, # 5
  21. Vector2i(-1, 1), # 6
  22. Vector2i.LEFT # 7
  23. ]
  24. func _process(_delta: float) -> void:
  25. $Point.frame = int(start_point == 0)
  26. visible = not (invisible and LevelEditor.playing_level)
  27. if editing and Global.current_game_mode == Global.GameMode.LEVEL_EDITOR:
  28. if Input.is_action_just_pressed("editor_open_menu") or Input.is_action_just_pressed("ui_cancel"):
  29. editing = false
  30. Global.level_editor.current_state = LevelEditor.EditorState.IDLE
  31. update_pieces()
  32. func _ready() -> void:
  33. for i in path:
  34. add_piece(i, false)
  35. update_pieces()
  36. func update_pieces() -> void:
  37. var idx := 0
  38. for i in $Pieces.get_children():
  39. i.idx = idx
  40. i.editing = idx >= path.size() and editing
  41. if idx > 0:
  42. i.starting_direction = -path[idx - 1]
  43. else:
  44. i.starting_direction = Vector2i.ZERO
  45. if idx <= path.size() - 1:
  46. i.connecting_direction = path[idx]
  47. else:
  48. i.connecting_direction = Vector2i.ZERO
  49. i.update_direction_textures()
  50. idx += 1
  51. func add_piece(new_direction := Vector2i.ZERO, add_to_arr := true) -> void:
  52. var piece = TRACK_PIECE.instantiate()
  53. var next_position := new_direction * 16
  54. for i in length:
  55. next_position += path[i] * 16
  56. piece.position = next_position
  57. $Pieces.add_child(piece)
  58. piece.owner = self
  59. pieces.append(piece)
  60. piece.idx = length
  61. piece.reset_physics_interpolation()
  62. if add_to_arr:
  63. path.append(new_direction)
  64. length += 1
  65. update_pieces()
  66. func remove_last_piece() -> void:
  67. $Pieces.get_child($Pieces.get_child_count() - 1).queue_free()
  68. await get_tree().process_frame
  69. path.pop_back()
  70. pieces.pop_back()
  71. length -= 1
  72. update_pieces()