Files
miti.sh/html/images/space.svg

636 lines
19 KiB
XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="-200 -150 400 300" version="1.1" xmlns="http://www.w3.org/2000/svg">
<style>
foreignObject {
font-size: 4pt;
font-family: courier;
}
#info {
position: absolute;
right: 0px;
padding: 1px;
}
#pointer {
position: absolute;
right: 0px;
bottom: 0px;
padding: 1px;
}
rect#bg {
fill: gray;
}
.ship circle {
fill: white;
}
circle.bullet {
fill: yellow;
}
#triangles polygon {
fill-opacity: 0.2;
stroke-width: 1px;
fill: none;
stroke: none;
}
#triangles polygon.clockwise-orientation {
fill: white;
stroke: red;
}
#triangles polygon.obtuse {
stroke: orangered;
stroke-dasharray: 5 10;
}
#triangles polygon.anti-clockwise {
stroke: orange;
stroke-dasharray: 1 5;
}
#edges line {
stroke: gold;
}
#legs {
display: none;
}
</style>
<rect id="bg" x="-200" y="-150" width="400" height="300"/>
<g class="ship">
<line id="cannon" x1="0" y1="0" x2="0" y2="8" stroke="black"/>
<circle id="body" cx="0" cy="0" r="5"/>
<g id="legs">
<path d="M 3 2 l 2 2 v 2 m -2 0 h 4" stroke="black" fill="none" />
<path d="M -3 2 l -2 2 v 2 m -2 0 h 4" stroke="black" fill="none" />
</g>
</g>
<!-- <polygon class="wall" points="20,20 40,20 40,40 20,40" /> -->
<!-- <polygon class="wall" points="-10,-30 -10,-40 30,-50 60,-30 80,0 150,0 150,10 60,50 -10,40 -20,20 20,20 20,-20" /> -->
<!-- <polygon class="wall" points="-130,-80 -40,-70 -70,-10 -100,40 -120,100" /> -->
<g>
<polygon class="wall" points="-130,-80 -40,-70 -70,-10" />
<polygon class="wall" points="50,70 90,-10 130,70" />
</g>
<g id="triangles"></g>
<g id="edges"></g>
<g id="bullets"></g>
<foreignObject x="-200" y="-150" width="100%" height="100%">
<div id="info" xmlns="http://www.w3.org/1999/xhtml">
<span id="time" xmlns="http://www.w3.org/1999/xhtml">0</span> s
<span id="fps" xmlns="http://www.w3.org/1999/xhtml">-</span> fps
</div>
<ul xmlns="http://www.w3.org/1999/xhtml">
<li xmlns="http://www.w3.org/1999/xhtml">bounce off walls/border</li>
<li xmlns="http://www.w3.org/1999/xhtml">gravity</li>
<li xmlns="http://www.w3.org/1999/xhtml">complete surround by wall</li>
<li xmlns="http://www.w3.org/1999/xhtml">fall off screen after crash</li>
<li xmlns="http://www.w3.org/1999/xhtml">make ship a helicopter</li>
<li xmlns="http://www.w3.org/1999/xhtml">use paths for walls</li>
<li xmlns="http://www.w3.org/1999/xhtml">multiple walls</li>
<li xmlns="http://www.w3.org/1999/xhtml">no walls</li>
<li xmlns="http://www.w3.org/1999/xhtml">stop reading data from elements</li>
<li xmlns="http://www.w3.org/1999/xhtml">ability to land</li>
<li xmlns="http://www.w3.org/1999/xhtml">gravity</li>
<li xmlns="http://www.w3.org/1999/xhtml">limited fuel</li>
<li xmlns="http://www.w3.org/1999/xhtml">additional cannon firing modes</li>
</ul>
<pre id="debug" xmlns="http://www.w3.org/1999/xhtml"></pre>
<div id="pointer" xmlns="http://www.w3.org/1999/xhtml">
x: <span class="x" xmlns="http://www.w3.org/1999/xhtml">-</span>,
y: <span class="y" xmlns="http://www.w3.org/1999/xhtml">-</span>
</div>
</foreignObject>
<script type="text/javascript">//<![CDATA[
const namespaceURIsvg = 'http://www.w3.org/2000/svg';
const degsRegex = /(-?\d*\.{0,1}\d+)deg/g;
const regex = /(-?\d*\.{0,1}\d+)px/g;
const bullets = [];
const halfPi = Math.PI / 2;
const maxSpeed = 100;
const drawCollisionLines = true;
let previous, zero, frameCount = 0;
let position = [0, 0]; // meters
let velocity = [0, 0]; // meters per second
let acceleration = [0, 0]; // meters per second per second
let friction = 0;
let rotate = 0;
let rotationSpeed = 0.25;
let started = false;
let restart = false;
let isReadingKeys = true;
const svg = document.querySelector('svg');
const fps = document.querySelector("#fps");
const time = document.querySelector("#time");
const debug = document.querySelector("#debug");
const ship = document.querySelector(".ship");
const gun = ship.querySelector('#cannon');
const shipBody = ship.querySelector("#body");
const walls = document.querySelectorAll('.wall');
const bulletsContainer = document.querySelector("#bullets");
const triangleContainer = document.querySelector('#triangles');
const edgeContainer = document.querySelector('#edges');
const bulletPt = svg.createSVGPoint();
const cornerPt = svg.createSVGPoint();
const allWallCorners = [...walls].map(wall =>
wall.getAttribute('points').split(' ').map(coords => {
const [x, y] = coords.split(',');
return [+x, +y];
}
));
const allEdgePts = allWallCorners.map(w =>
w.map((pt, i, arr) => [pt, arr[(i + 1) % arr.length]])
);
const allStartingEdges = findAllEdges(allEdgePts, position);
function distance(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}
function drawAllEdges(walls) {
walls.forEach(edges => drawEdges(edges));
}
function drawEdges(pts) {
let edges = pts.map(e => e.join(' '));
edges.forEach(e => {
const [x, y] = e.split(' ');
const [x1, y1] = x.split(',');
const [x2, y2] = y.split(',');
const el = document.createElementNS(namespaceURIsvg, 'line');
el.setAttribute('x1', x1);
el.setAttribute('y1', y1);
el.setAttribute('x2', x2);
el.setAttribute('y2', y2);
edgeContainer.appendChild(el)
});
}
function drawTriangles(container, walls, [positionX, positionY]) {
walls.forEach(pts =>
pts.forEach(([[x1, y1], [x2, y2]]) => {
const el = document.createElementNS(namespaceURIsvg, 'polygon');
const attr = `${x1},${y1} ${x2},${y2} ${positionX},${positionY}`
el.setAttribute('points', attr);
container.appendChild(el);
})
);
}
// Triangle has a clockwise orientation
function isClockwise([xa, ya], [xb, yb], [xc, yc]) {
// https://en.wikipedia.org/wiki/Curve_orientation#Practical_considerations
// Determinant for a convex polygon
const det = (+xb - +xa) * (+yc - +ya) - (+xc - +xa) * (+yb - +ya);
return det < 0;
}
function isAcute([xa, ya], [xb, yb], [xc, yc]) {
const da = distance(xa, ya, xc, yc);
const db = distance(xb, yb, xc, yc);
const dc = distance(xa, ya, xb, yb);
// https://en.wikipedia.org/wiki/Law_of_cosines
// Solve for angles alpha and beta with inverse cosine (arccosine)
const alpha = Math.acos((db ** 2 + dc ** 2 - da ** 2) / (2 * db * dc));
const beta = Math.acos((da ** 2 + dc ** 2 - db ** 2) / (2 * da * dc));
return alpha < halfPi && beta < halfPi;
}
function findEdges(verts, [xc, yc]) {
return verts.reduce((acc, [a, b]) => {
const isFound = [isClockwise, isAcute].every(c => c(a, b, [xc, yc]));
// return isFound ? [...acc, `${xa},${ya} ${xb},${yb}`] : acc;
return isFound ? [...acc, `${a[0]},${a[1]} ${b[0]},${b[1]}`] : acc;
}, []);
}
function findAllEdges(verts, [xc, yc]) {
return verts.reduce((acc, points) => {
points.forEach(([a, b]) => {
const isFound = [isClockwise, isAcute].every(c => c(a, b, [xc, yc]));
if (isFound) acc.push(`${a[0]},${a[1]} ${b[0]},${b[1]}`);
});
return acc;
}, []);
}
function updateTriangles([positionX, positionY]) {
const delim = ' ';
const className = 'clockwise-orientation';
if (!triangleContainer.childElementCount)
drawTriangles(triangleContainer, allEdgePts, position);
const triangles = triangleContainer.querySelectorAll('polygon');
triangles.forEach(t => {
const attr = t.getAttribute('points').split(delim);
const [a, b,] = attr.map(t => t.split(','));
const cw = isClockwise(a, b, [positionX, positionY]);
const acute = isAcute(a, b, [positionX, positionY]);
const pos = `${positionX},${positionY}`;
if (pos !== attr.pop()) {
attr.push(pos);
t.setAttribute('points', attr.join(delim));
}
t.classList[cw && acute ? "add" : "remove"](className);
t.classList[cw && !acute ? "add" : "remove"]("obtuse");
t.classList[!cw ? "add" : "remove"]("anti-clockwise");
});
}
function wrapPos(positionX, positionY) {
let x, y;
if (positionY > 150) y = positionY - 300;
else if (positionY < -150) y = positionY + 300;
else y = positionY;
if (positionX > 200) x = positionX - 400;
else if (positionX < -200) x = positionX + 400;
else x = positionX;
return [x, y];
}
function fireBullet(x, y, velocity) {
const speed = 200; // meters per second
const degrees = getRotate(gun);
const radians = degrees * Math.PI / 180; // toFixed(15)?
const vx = -Math.sin(radians);
const vy = Math.cos(radians);
const bulletTimeout = 5000; // miliseconds
const cannonLength = 8;
const el = document.createElementNS(namespaceURIsvg, 'circle');
el.classList.add('bullet');
el.setAttribute('r', 1);
el.setAttribute('cx', 0);
el.setAttribute('cy', 0);
const bullet = {
x: x + vx * cannonLength,
y: y + vy * cannonLength,
vx: vx * speed + velocity[0],
vy: vy * speed + velocity[1],
time: bulletTimeout,
node: bulletsContainer.appendChild(el)
}
bullets.push(bullet);
}
function getTranslate(el) {
let x, y;
if (el.style.transform.length === 0) {
x = 0;
y = 0;
} else {
[[, x], [, y] = ["0px", "0"]] = [...el.style.transform.matchAll(regex)];
}
return [+x, +y];
}
function getRotate(el) {
let [[, degrees] = ["0deg", "0"]] = [...el.style.transform.matchAll(degsRegex)];
return +degrees;
}
function updateBullets(elapsed) {
const deleteCount = 1;
[...bullets].forEach((bullet, index) => {
bullet.time -= elapsed;
const x = bullet.x + 0.001 * elapsed * bullet.vx;
const y = bullet.y + 0.001 * elapsed * bullet.vy;
bulletPt.x = x;
bulletPt.y = y;
if (bullet.time > 0 && ![...walls].some(w => w.isPointInFill(bulletPt))) {
[bullet.x, bullet.y] = wrapPos(x, y);
bullet.node.style.transform = `translate(${bullet.x}px, ${bullet.y}px)`;
} else {
bullet.node.remove();
bullets.splice(index, deleteCount);
}
});
}
function detectEdgeCollision([xc, yc], edge) {
const shipRadius = 5;
const [[xa, ya], [xb, yb]] = edge.split(' ').map(n => n.split(',').map(n => +n));
const da = distance(xa, ya, xc, yc);
const db = distance(xb, yb, xc, yc);
// TODO: calculate this one ahead of time
const dc = distance(xa, ya, xb, yb);
// https://en.wikipedia.org/wiki/Altitude_(triangle)#Altitude_in_terms_of_the_sides
// Find altitude of side c (the base)
const s = (1 / 2) * (da + db + dc);
const hc = (2 / dc) * Math.sqrt(s * (s - da) * (s - db) * (s - dc));
return hc <= shipRadius;
}
function detectCornerCollision([xc, yc], [x, y]) {
cornerPt.x = x - xc;
cornerPt.y = y - yc;
return shipBody.isPointInFill(cornerPt);
}
function detectCollisions(position, walls, edges) {
return [
[walls, wall => wall.some(corner => detectCornerCollision(position, corner))],
[edges, edge => detectEdgeCollision(position, edge)]
].some(([t, f]) => t.some(f))
}
function updateShip(elapsed) {
const degrees = getRotate(gun);
if (rotate > 0) gun.style.transform = `rotate(${(+degrees + rotationSpeed * elapsed) % 360}deg)`;
else if (rotate < 0) gun.style.transform = `rotate(${(+degrees - rotationSpeed * elapsed) % 360}deg)`;
let [velocityX, velocityY] = restart ? [0, 0] : velocity;
let [accelerationX, accelerationY] = restart ? [0, 0] : acceleration;
if (velocityX > 0) accelerationX += -friction;
else if (velocityX < 0) accelerationX += friction;
if (velocityY > 0) accelerationY += -friction;
else if (velocityY < 0) accelerationY += friction;
velocityX = velocityX > 0 && velocityX + accelerationX < 0 ? 0 : velocityX + accelerationX;
velocityY = velocityY > 0 && velocityY + accelerationY < 0 ? 0 : velocityY + accelerationY;
velocity = [velocityX, velocityY];
if (velocity[0] > maxSpeed) velocity[0] = maxSpeed;
else if (velocity[0] < -maxSpeed) velocity[0] = -maxSpeed
if (velocity[1] > maxSpeed) velocity[1] = maxSpeed;
else if (velocity[1] < -maxSpeed) velocity[1] = -maxSpeed
const changeX = 0.001 * elapsed * velocityX;
const changeY = 0.001 * elapsed * velocityY;
let [x, y] = getTranslate(ship);
let position = [positionX, positionY] = restart ? [0, 0] : wrapPos(changeX + x, changeY + y);
ship.style.transform = `translate(${positionX}px, ${positionY}px)`;
return position;
}
function updateEdges(position) {
const collisionEdges = findAllEdges(allEdgePts, position);
// console.log(collisionEdges);
[...edgeContainer.children].forEach(l => {
const x1 = l.getAttribute('x1');
const y1 = l.getAttribute('y1');
const x2 = l.getAttribute('x2');
const y2 = l.getAttribute('y2');
const edge = `${x1},${y1} ${x2},${y2}`;
if (collisionEdges.includes(edge))
if ([
edgeContainer.childElementCount <= allStartingEdges.length,
!allStartingEdges.includes(edge)
].some(c => c))
l.remove();
});
}
function firstFrame(timestamp) {
zero = timestamp;
zeroForTimer = timestamp;
previous = timestamp;
animate(timestamp);
}
function animate(timestamp) {
const elapsed = timestamp - previous;
const delta = timestamp - zero;
let degrees = getRotate(gun);
previous = timestamp;
time.innerText = ((timestamp - zeroForTimer) * 0.001).toFixed(3);
if (delta >= 1000) {
fps.innerText = frameCount;
// debug.innerText = `velocity ${velocity}\n`
// + 'bullets\nx\ty\tvx\tvy\n'
// + bullets.map(b => {
// return `${b.x.toFixed(2)}\t${b.y.toFixed(2)}\t${b.vx.toFixed(2)}\t${b.vy.toFixed(2)}`;
// }).join("\n");
zero = timestamp;
frameCount = 0;
} else {
frameCount++;
}
position = updateShip(elapsed);
updateBullets(elapsed);
updateEdges(position);
if (drawCollisionLines) updateTriangles(position);
if (restart) {
restart = false;
[...edgeContainer.children].forEach(c => c.remove());;
drawAllEdges(allEdgePts);
}
const collision = detectCollisions(position, allWallCorners, findAllEdges(allEdgePts, position));
walls.forEach(w => w.setAttribute('fill', collision ? 'red' : 'black'));
if (collision) {
// restart game
zeroForTimer = timestamp;
restart = true;
started = false;
isReadingKeys = false;
}
// if (+y < 200)
// if (timestamp < 10000)
if (edgeContainer.childElementCount > 0 && started)
requestAnimationFrame(t => animate(t));
}
// drawEdges(edgePts);
drawAllEdges(allEdgePts);
let force = 1;
let spacePressed = false;
let upPressed = false;
let downPressed = false;
let leftPressed = false;
let rightPressed = false;
let rotateCWPressed = false;
let rotateCCWPressed = false;
document.addEventListener("keydown", function(e) {
if (!isReadingKeys) return;
if (!started && !restart) {
started = true;
requestAnimationFrame(firstFrame);
} else if (restart) {
requestAnimationFrame(firstFrame);
}
switch (e.code) {
case "Space":
if (!spacePressed) {
spacePressed = true;
const [x, y] = getTranslate(ship);
fireBullet(x, y, velocity);
}
break;
case "KeyW":
case "ArrowUp":
if (!upPressed) {
upPressed = true;
acceleration[1] += -force;
}
break;
case "KeyS":
case "ArrowDown":
if (!downPressed) {
downPressed = true;
acceleration[1] += force;
}
break;
case "KeyA":
case "ArrowLeft":
if (!leftPressed) {
leftPressed = true;
acceleration[0] += -force;
}
break;
case "KeyD":
case "ArrowRight":
if (!rightPressed) {
rightPressed = true;
acceleration[0] += force;
}
break;
case "KeyQ":
case "Comma":
if (!rotateCCWPressed) {
rotateCCWPressed = true;
rotate += -1;
}
break;
case "KeyE":
case "Period":
if (!rotateCWPressed) {
rotateCWPressed = true;
rotate += 1;
}
break;
}
});
document.addEventListener("keyup", function(e) {
isReadingKeys = true;
switch (e.code) {
case "Space":
spacePressed = false;
break;
case "KeyW":
case "ArrowUp":
if (upPressed) {
upPressed = false;
acceleration[1] -= -force;
}
break;
case "KeyS":
case "ArrowDown":
if (downPressed) {
downPressed = false;
acceleration[1] -= force;
}
break;
case "KeyA":
case "ArrowLeft":
if (leftPressed) {
leftPressed = false;
acceleration[0] -= -force;
}
break;
case "KeyD":
case "ArrowRight":
if (rightPressed) {
rightPressed = false;
acceleration[0] -= force;
}
break;
case "KeyQ":
case "Comma":
if (rotateCCWPressed) {
rotateCCWPressed = false;
rotate -= -1;
}
break;
case "KeyE":
case "Period":
if (rotateCWPressed) {
rotateCWPressed = false;
rotate -= 1;
}
break;
}
});
const bg = svg.querySelector('#bg');
const pointer = svg.querySelector('#pointer');
const xp = pointer.querySelector('.x');
const yp = pointer.querySelector('.y');
const pointerPt = svg.createSVGPoint();
svg.addEventListener("pointermove", function({ clientX, clientY }) {
pointerPt.x = clientX;
pointerPt.y = clientY;
const svgP = pointerPt.matrixTransform(svg.getScreenCTM().inverse());
if (bg.isPointInFill(svgP)) {
xp.innerText = Math.trunc(svgP.x);
yp.innerText = Math.trunc(svgP.y);
}
});
//]]></script>
</svg>