let mouseDown = false; let mouseDownEver = false; document.onmousedown = function(e) { if (e.button === 0) { mouseDown = true; mouseDownEver = true; } }; document.onmouseup = function(e) { if (e.button === 0) { mouseDown = false; document.getElementById("slingshot").classList.add("ungrabbed"); sendNudge(-Math.floor(e.pageX - window.innerWidth / 2), Math.floor(e.pageY - window.innerHeight / 2)); } }; document.ontouchend = function(e) { document.getElementById("slingshot").classList.add("ungrabbed"); sendNudge(-Math.floor(e.changedTouches[0].clientX - window.innerWidth / 2), Math.floor(e.changedTouches[0].clientY - (window.innerHeight / 2))); }; document.ontouchstart = function(e) { e.preventDefault(); e.stopPropagation(); }; function distance(p1, p2) { return Math.sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2); } document.addEventListener("mousemove", (e) => { if (mouseDown) { document.getElementById("slingshot").classList.remove("ungrabbed"); cursorX = e.pageX; cursorY = window.innerHeight - e.pageY; const slingshot = document.getElementById("slingshot"); slingshot.style.width = distance({x: cursorX, y: cursorY}, { x: window.innerWidth / 2, y: window.innerHeight / 2 }) + "px"; const angle = cursorX >= window.innerWidth / 2 ? -Math.atan((window.innerHeight / 2 - cursorY) / (window.innerWidth / 2 - cursorX)) : (-Math.atan((window.innerHeight / 2 - cursorY) / (window.innerWidth / 2 - cursorX)) - Math.PI); slingshot.style.transform = "rotate(" + angle + "rad)"; } }); document.addEventListener("touchmove", (e) => { document.getElementById("slingshot").classList.remove("ungrabbed"); cursorX = e.touches[0].clientX; cursorY = window.innerHeight - e.touches[0].clientY; const slingshot = document.getElementById("slingshot"); slingshot.style.width = distance({x: cursorX, y: cursorY}, {x: window.innerWidth/2, y: window.innerHeight/2}) + "px"; const angle = cursorX >= window.innerWidth/2 ? -Math.atan((window.innerHeight/2 - cursorY)/(window.innerWidth/2 - cursorX)) : (-Math.atan((window.innerHeight/2 - cursorY)/(window.innerWidth/2 - cursorX)) - Math.PI); slingshot.style.transform = "rotate(" + angle + "rad)"; }); function sendNudge(x, y) { fetch("http://localhost:8080", { method: "POST", headers: {"Content-Type": "application/json"}, referrer: "no-referrer", body: JSON.stringify([x, y]) }) .then((response) => { if (![200, 201, 204].includes(response.status)) { throw new Error("Nudge request failed with http status: " + response.status) } }) .catch((e) => { console.log("Failed to send nudge request " + e) }); }