extends Node2D
const PhysicsFunc = preload("res://src/Utilities/Physic/PhysicsFunc.gd")

#Array of RayCast2D
onready var trigger_rays = $FlyingLaserCutterBody/Triggers.get_children()
onready var body = $FlyingLaserCutterBody
onready var local_facing: Vector2 = Vector2.RIGHT
onready var global_facing: Vector2 = local_facing.rotated(transform.get_rotation())
onready var slide_friction = 1.5

var flyoff_triggered = false
var velocity = 1
var max_velocity = 200
var acceleration_force = 1200
var mass = 10

# TODO Returing Laser cutter has broken collision and infinite inertia
# Maybe keep returning paths free and crush player when in the way

func _ready() -> void:
	$FlyingLaserCutterBody/Sprite/AnimationPlayer.play("default")


func _physics_process(delta: float) -> void:
	if !flyoff_triggered:
		for ray in trigger_rays:
			if ray.is_colliding():
				var collider = ray.get_collider()
				if collider.is_in_group("player"):
					flyoff_triggered = true
					body.set("motion/sync_to_physics", false)
					break
		if body.position.x > 0:
			velocity=1
			body.position.x += (max_velocity/3)*-1*delta
	else:
		velocity = PhysicsFunc.two_step_euler(
			velocity, acceleration_force, mass, delta
		)
		velocity = clamp(velocity, 0, max_velocity)
		var collision = body.move_and_collide(velocity*global_facing*delta,true)
		if collision != null:
			if !collision.collider.is_in_group("player"):
				body.set("motion/sync_to_physics", true)
				flyoff_triggered = false
