/** * Shared camera-plane projection (FOV 90°). * Rays use dir + plane*camX (camX in [-1,1]); depths are perpendicular * (along forward), so walls/floor/sprites/z-buffer stay consistent and * fish-eye from equal-angle rays + Euclidean depth is avoided. */ var Camera = { /** Half FOV in radians (π/4 → full FOV 90°). */ HALF_FOV: Math.PI / 4, tanHalfFov: function () { return Math.tan(this.HALF_FOV); }, forward: function (rot) { return { x: Math.cos(rot), y: Math.sin(rot) }; }, /** * Camera plane vector (perpendicular to forward, length = tan(halfFov)). * World +Y is south; left-handed screen: +plane = screen right. */ plane: function (rot) { var t = this.tanHalfFov(); var fx = Math.cos(rot); var fy = Math.sin(rot); // right = (-fy, fx) so that forward×right points "up" in XY… // For +X east +Y south, facing +X: right should be +Y (south) = screen right when looking east? // Looking east (+X): screen right = south (+Y). right=(-fy,fx)=(0,1). plane = right * tan. return { x: -fy * t, y: fx * t }; }, /** camX in [-1,1] from screen x / column index. */ camXFromScreen: function (sx, screenW) { return (2 * sx / screenW) - 1; }, camXFromColumn: function (col, cols) { return -1 + (2 * (col + 0.5) / cols); }, /** Unnormalized ray direction for camera-plane casting. */ rayDir: function (rot, camX) { var f = this.forward(rot); var p = this.plane(rot); return { x: f.x + p.x * camX, y: f.y + p.y * camX }; }, /** Angle of camera-plane ray (for World.rayCast which takes a radian). */ rayAngle: function (rot, camX) { var d = this.rayDir(rot, camX); return Math.atan2(d.y, d.x); }, /** * Perpendicular depth of a world point relative to the camera. * Positive in front; use for sprite size, z-buffer, occlusion. */ perpDepth: function (worldX, worldY, playerX, playerY, rot) { var f = this.forward(rot); return (worldX - playerX) * f.x + (worldY - playerY) * f.y; }, /** * Perp depth from Euclidean ray length and the ray's camX * (euclid * cos(atan(camX*tanHalf)) = euclid / length(rayDir) * …). * For a hit along rayDir: perp = euclid * (forward·normalize(rayDir)). */ perpFromEuclid: function (euclidDist, rot, camX) { var d = this.rayDir(rot, camX); var len = Math.sqrt(d.x * d.x + d.y * d.y); if (len < 1e-8) { return euclidDist; } var f = this.forward(rot); var cosA = (d.x * f.x + d.y * f.y) / len; return euclidDist * cosA; }, /** * Project world point to screen X (pixels) and perp depth. * Returns null if behind camera. */ projectSprite: function (worldX, worldY, playerX, playerY, rot, screenW) { var depth = this.perpDepth(worldX, worldY, playerX, playerY, rot); if (depth <= 0.05) { return null; } var f = this.forward(rot); var t = this.tanHalfFov(); // screen-right axis (= plane / tanHalf) var rx = -f.y; var ry = f.x; var lat = (worldX - playerX) * rx + (worldY - playerY) * ry; var screenX = (screenW / 2) * (1 + (lat / depth) / t); return { screenX: screenX, depth: depth, lat: lat }; } }; if (typeof module !== "undefined" && module.exports) { module.exports = Camera; }