Skip to content

gitflarePublicPartly agent-ready40

orbit-duel

Real-time two-player orbital combat game on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence0413e56
JavaScript54 lines2.2 KB
const keys = new Set();const out = { rotate: 0, thrust: 0, fire: 0 };export const input = { touch: { active: false, baseX: 0, baseY: 0, x: 0, y: 0, fire: false } };let heading = 0, hasHeading = false; export function initInput(canvas) {  addEventListener('keydown', (e) => { keys.add(e.code); if (e.code === 'Space' || e.code.startsWith('Arrow')) e.preventDefault(); });  addEventListener('keyup', (e) => keys.delete(e.code));  addEventListener('blur', () => keys.clear());  const T = input.touch;  let joyId = -1, fireId = -1;  const rect = () => canvas.getBoundingClientRect();  canvas.addEventListener('touchstart', (e) => {    e.preventDefault();    const r = rect();    for (const t of e.changedTouches) {      const x = t.clientX - r.left, y = t.clientY - r.top;      if (x > r.width * 0.6) { fireId = t.identifier; T.fire = true; }      else if (joyId < 0) { joyId = t.identifier; T.active = true; T.baseX = T.x = x; T.baseY = T.y = y; hasHeading = false; }    }  }, { passive: false });  canvas.addEventListener('touchmove', (e) => {    e.preventDefault();    const r = rect();    for (const t of e.changedTouches) {      if (t.identifier !== joyId) continue;      T.x = t.clientX - r.left; T.y = t.clientY - r.top;      const dx = T.x - T.baseX, dy = T.y - T.baseY;      if (Math.hypot(dx, dy) > 40) { heading = Math.atan2(dy, dx); hasHeading = true; } else hasHeading = false;    }  }, { passive: false });  const end = (e) => {    for (const t of e.changedTouches) {      if (t.identifier === joyId) { joyId = -1; T.active = false; hasHeading = false; }      else if (t.identifier === fireId) { fireId = -1; T.fire = false; }    }  };  canvas.addEventListener('touchend', end);  canvas.addEventListener('touchcancel', end);} export function readInput(angle) {  let r = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);  let th = keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0;  if (hasHeading) {    const d = Math.atan2(Math.sin(heading - angle), Math.cos(heading - angle));    r = d > 0.1 ? 1 : d < -0.1 ? -1 : 0;    th = 1;  }  out.rotate = r; out.thrust = th; input.thrusting = th === 1;  out.fire = keys.has('Space') || input.touch.fire ? 1 : 0;  return out;}