starcheese/laser.gd

75 lines
2.2 KiB
GDScript3
Raw Normal View History

2024-10-01 16:43:34 +02:00
extends Node2D
@export var laser_range: float = 800.0
@export var laser_damage: float = 0.2
@export var hardpoint_id: String = "HardPoint1" # Identifier for the hardpoint to attach this laser
var hardpoint = null # Reference to the attached hardpoint
var is_firing = false # Track the laser's firing state
var current_damage_output: float = 0.0 # Track the current damage output
var event_bus: EventBus
2024-10-01 16:43:34 +02:00
func _ready():
# Register the laser to the "weapons" group
add_to_group("weapons")
# Connect to the correct hardpoint when ready
call_deferred("_connect_to_hardpoint")
event_bus = get_node("/root/Main/MainEventBus")
2024-10-01 16:43:34 +02:00
# Initialize LaserLine2D with two points (origin and target)
$LaserLine2D.clear_points()
$LaserLine2D.add_point(Vector2.ZERO) # Origin point
$LaserLine2D.add_point(Vector2.ZERO) # Target point (initially the same as origin)
$DamageOutputLabel.text = str(current_damage_output)
# Connect the laser to the appropriate hardpoint
func _connect_to_hardpoint():
var hardpoints = get_tree().get_nodes_in_group("hardpoints")
for h in hardpoints:
if h.hardpoint_id == hardpoint_id:
hardpoint = h
h.attach_weapon(self)
break
func fire():
is_firing = true
current_damage_output = laser_damage
$DamageOutputLabel.text = str(current_damage_output)
2024-10-01 16:43:34 +02:00
_process_laser(true)
func cease_fire():
is_firing = false
current_damage_output = 0.0
$DamageOutputLabel.text = str(current_damage_output)
2024-10-01 16:43:34 +02:00
_process_laser(false)
func _process(delta: float) -> void:
if is_firing:
_process_laser(true)
func _process_laser(active: bool):
var raycast = $LaserBeam2D
raycast.enabled = active
if active:
raycast.force_raycast_update()
if raycast.is_colliding():
var collision_point = raycast.get_collision_point()
$LaserLine2D.set_point_position(0, Vector2.ZERO)
$LaserLine2D.set_point_position(1, to_local(collision_point))
2024-10-01 16:43:34 +02:00
var collider = raycast.get_collider()
if collider:
var damage_event = DamageEvent.new(laser_damage, collider)
event_bus.publish(get_node("/root/Main/DamageEventScope"), damage_event)
2024-10-01 16:43:34 +02:00
else:
$LaserLine2D.set_point_position(1, Vector2(0, -laser_range))
2024-10-01 16:43:34 +02:00
else:
$LaserLine2D.clear_points()
$LaserLine2D.add_point(Vector2.ZERO)
$LaserLine2D.add_point(Vector2.ZERO)