JSFiddle - React, Tailwind, and code Playground

by darthdeus

HTML

<canvas id="canvas" height="200" width="200" tabindex="1"></canvas>
<div id="debug-text"></div>

JavaScript

var Direction = {
    UP: "up",
    DOWN: "down",
    LEFT: "left",
    RIGHT: "right"
};

// A ray is defined by its origin and direction.
function Ray(x, y, dir) {
    this.origin = {
        x: x,
        y: y
    };
    this.direction = dir;
}

Ray.from = function (origin, dir) {
    return new Ray(origin.x, origin.y, dir);
};

// AABB is defined by its top-left corner, width and height.
function AABB(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
}

function compareInterval(value, low, high) {
    // This shouldn't necessarily be required, but it allows us to just specify
    // the bounds of an interval, without checking which of the two is low and which is high.
    if (low > high) {
        var tmp = high;
        high = low;
        low = tmp;
    }

    // And then we simply check if the value lies outside of the interval
    if (value < low) {
        return -1;
    } else if (low <= value && value <= high) {
        return 0;
    } else if (value > high) {
        return 1;
    }
}

function intersect(ray, aabb) {
    switch (ray.direction) {
        case Direction.UP:
            if (ray.origin.y >= aabb.y + aabb.h) {
                if (compareInterval(ray.origin.x, aabb.x, aabb.x + aabb.w) == 0) {
                    return {
                        x: ray.origin.x,
                        y: aabb.y + aabb.h
                    };
                } else {
                    return null;
                }
            } else {
                return null;
            }
        case Direction.DOWN:
            if (ray.origin.y <= aabb.y) {
                if (compareInterval(ray.origin.x, aabb.x, aabb.x + aabb.w) == 0) {
                    return {
                        x: ray.origin.x,
                        y: aabb.y
                    };
                } else {
                    return null;
                }
            } else {
                return null;
            }
        case Direction.LEFT:
        ...