
extends Node2D

const MIN_X = 0
const MIN_Y = 0
const MAX_X = 800
const MAX_Y = 600

var trajectory = Vector2(0,1)
var speed = 50.0
var speed_derivative = 0.0

func _ready():
	set_process(true)

func _process(delta):
	set_position(next_wander(delta))

func next_wander(delta):
	var current_pos = get_position()
	
	if (current_pos.x < MIN_X and trajectory.x < 0 or current_pos.x > MAX_X and trajectory.x > 0):
		speed_derivative = -100
	
	if current_pos.y < MIN_Y:
		trajectory.y = 1
	elif current_pos.y > MAX_Y:
		trajectory.y = -1
	
	trajectory = slightly_random(trajectory, delta)
	
	speed_derivative += delta * rand_range(-100.0, 100.0)
	speed += delta * speed_derivative
	
	if (speed_derivative < -200.0):
		speed_derivative = -50.0
	elif (speed_derivative > 200.0):
		speed_derivative = 0.0
	
	if (speed < -0.2):
		speed = -speed * 2
		trajectory = -trajectory
		speed_derivative = 50.0
	if (speed > 110):
		speed = 100.0
		speed_derivative = 0.0
	
	if trajectory.x < -0.5:
		get_node("sprite").set_flip_h(false)
	elif trajectory.x > 0.5:
		get_node("sprite").set_flip_h(true)
	
	return get_position() + delta * trajectory * speed

func slightly_random(vec, delta):
	var x = (vec.x + delta * rand_range(-2.0, 2.0)) * 1.005
	var y = vec.y + delta * rand_range(-2.0, 2.0)
	var V = Vector2(x, y)
	return V.normalized()

