cosmic/scripts/Ship/ship.gd
2024-06-09 23:01:14 +03:00

70 lines
2.3 KiB
GDScript

extends Node2D
class_name Ship
## Emits when hull hp reaches zero.
signal destroyed
## Ship ID to define its type
@export var id: String
## Reference to the engine module
@onready var engine: ShipEngine = $Engine
## Reference to the hull module
@onready var hull: Hull = $HullHolder/Hull
## Reference to the shield module
@onready var shield: Shield = $Shield
## Reference to weapons node
@onready var weapons: Node2D = $Weapons
## Node beginning position
@onready var spawn_position: Vector2 = global_position
## Reference to the star system
@onready var star_system: StarSystem = get_tree().current_scene
## Faction which this ship belongs to
var faction : Game.Faction
func _ready() -> void:
star_system.ships.append(self)
hull.global_position = global_position
destroyed.connect(destroy_timeout)
destroyed.connect(star_system.on_ship_destroyed.bind(self))
hull.mouse_entered.connect(star_system.set_targeted_node.bind(self))
hull.mouse_exited.connect(star_system.clear_targeted_node)
func destroy_timeout():
destroy()
get_tree().create_timer(0.05).timeout.connect(hull.warp_to_position.bind(spawn_position))
## Reset all required variables
func destroy() -> void:
hull.hp = hull.max_hp
hull.linear_velocity = Vector2.ZERO
hull.angular_velocity = 0.0
shield.capacity = shield.max_capacity
## Swaps old hull with the new one
func change_hull(new_hull_id: String) -> void:
var hull_holder: Node = hull.get_parent()
var new_hull: Hull = Game.get_module(new_hull_id, 'hull').instantiate()
var old_hull: Hull = hull
hull_holder.add_child(new_hull)
hull = new_hull
hull.hp = old_hull.hp
get_tree().create_timer(0.05).timeout.connect(old_hull.queue_free)
## Swaps old engine with the new one
func change_engine(new_engine_id: String) -> void:
var new_engine: ShipEngine = Game.get_module(new_engine_id, 'engine').instantiate()
var old_engine: ShipEngine = engine
add_child(new_engine)
engine = new_engine
get_tree().create_timer(0.05).timeout.connect(old_engine.queue_free)
## Swaps old shield with the new one
func change_shield(new_shield_id: String) -> void:
var new_shield: Shield = Game.get_module(new_shield_id, 'shield').instantiate()
var old_shield: Shield = shield
add_child(new_shield)
shield = new_shield
get_tree().create_timer(0.05).timeout.connect(old_shield.queue_free)