37 lines
935 B
GDScript
37 lines
935 B
GDScript
extends Node2D
|
|
|
|
const SPEED_PER_DISTANCE = 15
|
|
const MAX_SPEED = 200
|
|
const MAX_DISTANCE_BEFORE_DETACH = 32
|
|
|
|
var attached: KinematicBody2D = null
|
|
var anchor_offset = Vector2.ZERO
|
|
|
|
func attach(node: KinematicBody2D):
|
|
attached = node
|
|
anchor_offset = -(node.global_position - self.global_position)
|
|
|
|
func detach():
|
|
attached = null
|
|
anchor_offset = Vector2.ZERO
|
|
|
|
func _physics_process(_delta):
|
|
if attached == null:
|
|
return
|
|
|
|
var anchor_relative_to_us = (attached.global_position + anchor_offset) - self.global_position
|
|
var distance = anchor_relative_to_us.length()
|
|
if distance < 0.1:
|
|
return
|
|
|
|
if distance > MAX_DISTANCE_BEFORE_DETACH:
|
|
attached = null
|
|
anchor_offset = Vector2.ZERO
|
|
$DetachSfx.pitch_scale = rand_range(0.9, 1.1)
|
|
$DetachSfx.play()
|
|
print("detached!")
|
|
return
|
|
|
|
var velocity = (-anchor_relative_to_us.normalized()) * min(MAX_SPEED, SPEED_PER_DISTANCE * distance)
|
|
var _lv = attached.move_and_slide(velocity)
|