extends CharacterBody2D

var lifeTime = 0.6

@onready var parent = get_parent()

var lastPos = null

var detecting = true

var partiDebounce = true

var target = null
var bodyOffset = Vector2.ZERO

func objectHit(body):
	if body != self:
		velocity = Vector2.ZERO
		parent.grappleStart()

func _physics_process(delta):
	if not lastPos:
		lastPos = position
	
	move_and_slide()
	
	if find_child("parti"):
		$"parti".emitting = (lastPos - position).length() > 0
	
	if detecting:
		if lifeTime <= 0:
			velocity = -velocity 
			parent.retractingProj.append({"proj": self, "retractStart": position, "retractDur": 0})
			parent.grappling = false
			parent.proj = null
			detecting = false
		lifeTime -= delta
		var space_state = get_world_2d().direct_space_state
	
		var query = PhysicsRayQueryParameters2D.create(lastPos, position, 3, [parent.get_parent().get_parent()])
		var result = space_state.intersect_ray(query)
		
		if result:
			detecting = false
			global_position = result.position
			target = result.collider
			bodyOffset = global_position - result.collider.global_position 
			objectHit(result.collider)
	elif parent.grappling and target:
		global_position = target.global_position + bodyOffset
	
	lastPos = global_position
