let shork_image = document.getElementById("shork");

let zoomies = 4;
let turnies = 0.2;

let shork = {x: 4, y: 8};
let rotation = 0;
let shork_init = transform(shork, -rotation);
shork_image.style.transform = `matrix(${shork_init.a}, ${shork_init.b}, ${shork_init.c}, ${shork_init.d}, ${shork_init.x}, ${shork_init.y})`;

let mouse = {x: 0, y: 0};
onmousemove = function(e){
	mouse.x = e.pageX;
	mouse.y = e.pageY;
}

let direction = 0;
let movement = 0;
let target = 0;

function move() { 
	direction = vector(shork, mouse);
	
	if (norm(direction) >= 4) {
		movement = scalar(angletovec(rotation), zoomies * norm(direction)/128);
		shork = add(shork, movement);
		target = angle(direction);
		rotation = interpolate(rotation, target, turnies) + Math.sin(norm(movement))/8;
	}

	let trans = transform(shork, -rotation);
	shork_image.style.transform = `matrix(${trans.a}, ${trans.b}, ${trans.c}, ${trans.d}, ${trans.x}, ${trans.y})`;

	setTimeout(move, 30);
}

shork_image.addEventListener("click", function(e) {move()}, {once: true});

function vector(a, b) {
	return {
		x: b.x - a.x,
		y: b.y - a.y
	};
}

function angle(v) {
	return Math.atan2(v.y, v.x);
}

function angletovec(a) {
	return {x: Math.cos(a), y: Math.sin(a)};
}

function norm(v) {
	return Math.sqrt(Math.pow(v.x, 2) + Math.pow(v.y, 2));
}

function unit(v) {
	let length = norm(v);

	if (length == 0) return {x: 0, y: 0};

	return {x: v.x / length, y: v.y / length};
}

function scalar(v, a) {
	return {x: v.x * a, y: v.y * a};
}

function add(v, u) {
	return {x: v.x + u.x, y: v.y + u.y};
}

function round(v) {
	return {x: Math.round(v.x), y: Math.round(v.y)};
}

function clamp(a, min, max) {
	if (a < min) return min;
	if (a > max) return max;
	return a;
}

function interpolate(a, b, c) {
	let d = Math.abs(a - b)
	if (d > Math.abs(a - b - 2 * Math.PI)) a = a - 2 * Math.PI;
	if (d > Math.abs(a - b + 2 * Math.PI)) a = a + 2 * Math.PI;

	if (a < b) a = clamp(a + c, a, b);
	if (a > b) a = clamp(a - c, b, a);

	a += 3 * Math.PI;
	a = a % (2 * Math.PI);
	a -= Math.PI;

	return a;
}

function transform(v, a) {
	return {a: Math.cos(a), b: -Math.sin(a), c: Math.sin(a), d: Math.cos(a), x: v.x, y: v.y};
}

