class_name Ship
extends RigidBody2D
# Common base script for ships

signal moved(speed: float)
signal thrusted(power: float)

const THRUST_STRENGTH: float = 400_000.0
const TORQUE_THRUST: float = 20.0
const MOVE_CEIL : float = 2.0
const THRUST_CEIL : float = 2.0

var current_force := Vector2.ZERO
var current_torque : float = 0.0


func _physics_process(delta):
	apply_central_force(current_force.rotated(rotation))
	apply_torque(current_torque)

	_vec_ceil_emit(linear_velocity, MOVE_CEIL, moved)
	_vec_ceil_emit(current_force, THRUST_CEIL, thrusted)

func _vec_ceil_emit(vec: Vector2, ceil: float, sig: Signal) -> void:
	var length_square: float = vec.length_squared()
	if length_square > ceil:
		sig.emit(sqrt(length_square))
	else:
		sig.emit(0.0)


func _on_command(dir: Vector2) -> void:
	_thrust(dir)


func _thrust(dir: Vector2) -> void:
	current_force = Vector2.UP * dir.y * THRUST_STRENGTH
	current_torque = dir.x * TORQUE_THRUST * THRUST_STRENGTH
