cosmic/scripts/State Machine/Kamikaze/WanderingState.gd
2024-05-12 21:19:44 +03:00

71 lines
2.4 KiB
GDScript

extends State
## Shortcut to get_parent().get_parent()
@onready var ship = get_parent().get_parent()
## Shortcut to current scene
@onready var star_system = get_tree().current_scene
## Timer which randomizes destination
@onready var update_timer = $UpdateDestination
## Radius in which ship will transit to attack state
@export var search_distance: float = 1024.0
## Ship will strive to achieve this angle
var destination_degrees: float = 0:
set(value):
if value > 180:
destination_degrees = value - 360
elif value < -180:
destination_degrees = 360 + value
else:
destination_degrees = value
## Delta to destination_degrees
var destination_difference: float = 1.0
var current_destination_difference: float:
set(value):
if value > 180:
current_destination_difference = value - 360
else:
current_destination_difference = value
## available map bounds (use with absolute position)
var available_bounds: Vector2
# for testing purposes only
var player_ship: PlayerShip = null
func _ready():
available_bounds = Vector2(star_system.width / 2, star_system.height / 2)
randomize()
func enter(_message):
update_timer.start()
get_tree().create_timer(0.02).timeout.connect(get_player_ship)
update_destination()
func process(_delta):
# checking if need to apply torque
current_destination_difference = destination_degrees - ship.hull.global_rotation_degrees
if abs(current_destination_difference) > destination_difference:
ship.engine.rotation_axis = clamp(current_destination_difference / 360 + 0.5 * sign(current_destination_difference), -1.0, 1.0)
else:
ship.engine.rotation_axis = 0.0
# making ship always accelerate
ship.engine.acceleration_axis = 1.0
# if ship is out of star system bounds, set destination angle to center
if abs(ship.global_position.x) > available_bounds.x or abs(ship.global_position.y) > available_bounds.y:
destination_degrees = rad_to_deg(ship.global_position.angle_to_point(Vector2.ZERO))
# if distance to player is less than scan radius
# TODO: rewrite this to more complex behavior
if player_ship != null:
var distance_to_player = ship.global_position.distance_to(player_ship.position)
if distance_to_player <= search_distance:
get_parent().transit("AttackState", {"target": player_ship})
func exit():
update_timer.stop()
## Set new random direction
func update_destination():
destination_degrees += randi_range(-180, 180)
func get_player_ship():
player_ship = star_system.player_ship