JSFiddle - React, Tailwind, and code Playground
JavaScript
var map = [
'xxxxxxxxxxxxxxx',
'x x x x',
'x xx xxx x x',
'x x x',
'xxxxxxxxxxxxxxx',
].join('').split('').map(function(s){
// spaces are open, xes are a random texture
if (s === ' ') return 0;
return 1+Math.floor(Math.random()*5);
});
function cast(px, py, angle) {
// delta of moving one unit forward on a line at angle
var dx = Math.cos(angle);
var dy = Math.sin(angle);
for (var i=0; i<10000; ++i) {
var x = Math.floor(px + dx);
var y = Math.floor(py);
if (map[x + y*width]) {
return {x:x, y:y};
}
x = Math.floor(px);
y = Math.floor(py + dy);
if (map[x + y*width]) {
return {x:x, y:y};
}
x = Math.floor(px + dx);
y = Math.floor(py + dy);
if (map[x + y*width]) {
return {x:x, y:y};
}
px += dx;
py += dy;
// oob
if (px > width || py > height) return null;
}
throw 'shouldnt really happen tbh';
}
function intersects(ax, ay, aax, aay, bx, by, bbx, bby, side){
var sax = aax - ax;
var say = aay - ay;
var sbx = bbx - bx;
var sby = bby - by;
var s = (-say * (ax - bx) + sax * (ay - by)) / (-sbx * say + sax * sby);
var t = ( sbx * (ay - by) - sby * (ax - bx)) / (-sbx * say + sax * sby);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
var x = ax + (t*sax);
var y = ay + (t*say);
return {x:x, y:y, side:side};
}
return null;
}
function collides(x1, y1, x2, y2, cx, cy) {
// which side may be hit
var rightward = x1 < x2;
var downward = y1 < y2;
// t will end up with the intersection coordinate, or null if there was no hit
var t = null;
if (downward) t = intersects(x1, y1, x2, y2, cx, cy, cx+1, cy, 'up');
if (rightward && !t) t = intersects(x1, y1, x2, y2, cx, cy, cx, cy+1, 'left');
if (!downward && !t) t = intersects(x1, y1, x2, y2, cx, cy+1, cx+1, cy+1, 'down');
if (!rightward && !t) t = intersects(x1, y1, x2,...