Prompt specification
Build or customize the Three.js 3D scene "Sneak a Parcel Past a Rotating Watcher" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Sneak a Parcel Past a Rotating Watcher
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sneak-a-parcel-past-a-rotating-watcher-x3462
Scene Description Prompt:
Create a nonviolent stealth puzzle with a slowly rotating observer and movable cover. Use explicit sight-range and occlusion rules, avoiding detection through solid walls. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (sneak-a-parcel-past-a-rotating-watcher-x3462):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Watch — Nonviolent Stealth Puzzle</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(12, 20, 32, 0.88);
--border: rgba(159, 205, 230, 0.2);
--text: #eaf5ff;
--muted: #9fb4c5;
--cyan: #66e2ff;
--green: #72f0a8;
--amber: #ffc45f;
--red: #ff657a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07101a;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(14px);
}
#mission {
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
padding: 18px;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 8px;
font-size: 25px;
line-height: 1.05;
}
.mission-copy {
margin: 0 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.status-row,
.stat-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.status-row {
margin-bottom: 9px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--green);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.09em;
}
.status::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.status.visible {
color: var(--red);
}
.mode {
color: var(--muted);
font-size: 11px;
text-align: right;
}
.meter {
height: 8px;
overflow: hidden;
background: rgba(255, 255, 255, 0.09);
border-radius: 20px;
}
#meterFill {
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--amber), var(--red));
transition: width 80ms linear;
}
.meter-label {
display: flex;
justify-content: space-between;
margin: 7px 0 14px;
color: var(--muted);
font-size: 11px;
}
.live-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.live-cell {
padding: 9px 10px;
background: rgba(255, 255, 255, 0.045);
border: 1px solid rgba(255, 255, 255, 0.055);
border-radius: 9px;
}
.live-cell span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.live-cell b {
font-size: 13px;
}
#rules {
top: 18px;
right: 18px;
width: min(320px, calc(100vw - 36px));
padding: 16px 17px;
}
#rules summary {
color: var(--text);
cursor: pointer;
font-size: 13px;
font-weight: 800;
list-style: none;
}
#rules summary::-webkit-details-marker {
display: none;
}
#rules summary::after {
float: right;
color: var(--cyan);
content: "+";
font-size: 18px;
line-height: 1;
}
#rules[open] summary::after {
content: "−";
}
.rule-list {
margin: 13px 0 0;
padding: 0;
list-style: none;
counter-reset: rule;
}
.rule-list li {
position: relative;
margin: 0 0 10px;
padding-left: 28px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
counter-increment: rule;
}
.rule-list li::before {
position: absolute;
top: 0;
left: 0;
display: grid;
width: 19px;
height: 19px;
place-items: center;
color: var(--cyan);
background: rgba(102, 226, 255, 0.1);
border-radius: 5px;
content: counter(rule);
font-size: 10px;
font-weight: 900;
}
.rule-list strong {
color: var(--text);
}
#help {
bottom: 18px;
left: 50%;
max-width: calc(100vw - 36px);
padding: 10px 16px;
color: var(--muted);
font-size: 11px;
line-height: 1.6;
text-align: center;
transform: translateX(-50%);
white-space: nowrap;
}
kbd {
display: inline-block;
min-width: 22px;
padding: 2px 6px;
color: var(--text);
background: rgba(255, 255, 255, 0.09);
border: 1px solid rgba(255, 255, 255, 0.14);
border-bottom-width: 2px;
border-radius: 5px;
font: 700 10px ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
}
#toast {
position: fixed;
z-index: 30;
bottom: 90px;
left: 50%;
max-width: min(520px, calc(100vw - 36px));
padding: 11px 16px;
color: var(--text);
background: rgba(10, 19, 31, 0.94);
border: 1px solid rgba(102, 226, 255, 0.3);
border-radius: 10px;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
font-size: 12px;
line-height: 1.4;
opacity: 0;
pointer-events: none;
text-align: center;
transform: translate(-50%, 8px);
transition: opacity 180ms, transform 180ms;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#flash,
#win {
position: fixed;
z-index: 40;
inset: 0;
display: grid;
place-items: center;
background: rgba(4, 8, 14, 0.76);
opacity: 0;
pointer-events: none;
transition: opacity 180ms;
}
#flash.show,
#win.show {
opacity: 1;
pointer-events: auto;
}
.modal {
width: min(430px, calc(100vw - 36px));
padding: 28px;
background: #101c2b;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 18px;
box-shadow: 0 30px 90px rgba(0, 0, 0, 0.55);
text-align: center;
}
.modal h2 {
margin: 8px 0;
font-size: 30px;
}
.modal p {
color: var(--muted);
font-size: 13px;
line-height: 1.6;
}
button {
padding: 11px 18px;
color: #07101a;
background: var(--cyan);
border: 0;
border-radius: 9px;
cursor: pointer;
font: 900 12px ui-sans-serif, system-ui, sans-serif;
letter-spacing: 0.03em;
}
button:hover {
filter: brightness(1.08);
}
#touchControls {
position: fixed;
z-index: 20;
right: 16px;
bottom: 16px;
display: none;
grid-template-columns: repeat(3, 48px);
grid-template-rows: repeat(3, 42px);
gap: 5px;
}
#touchControls button {
padding: 0;
color: var(--text);
background: rgba(14, 25, 40, 0.9);
border: 1px solid rgba(255, 255, 255, 0.16);
}
#touchControls .up {
grid-column: 2;
grid-row: 1;
}
#touchControls .left {
grid-column: 1;
grid-row: 2;
}
#touchControls .down {
grid-column: 2;
grid-row: 2;
}
#touchControls .right {
grid-column: 3;
grid-row: 2;
}
#touchControls .grab {
grid-column: 2;
grid-row: 3;
}
@media (pointer: coarse) {
#touchControls {
display: grid;
}
#help {
left: 18px;
max-width: calc(100vw - 180px);
overflow: hidden;
text-align: left;
white-space: normal;
}
}
@media (max-width: 720px) {
#mission {
width: 260px;
padding: 13px;
}
h1 {
font-size: 20px;
}
.mission-copy {
display: none;
}
#rules {
top: auto;
right: 12px;
bottom: 126px;
width: 255px;
}
#rules:not([open]) {
padding: 11px 14px;
}
#help {
font-size: 10px;
}
}
</style>
</head>
<body>
<section id="mission" class="panel">
<div class="eyebrow">Nonviolent stealth puzzle</div>
<h1>Voxel Watch</h1>
<p class="mission-copy">
Reach the green beacon in the upper-right chamber. The observer never
attacks; being fully spotted simply returns you to the start.
</p>
<div class="status-row">
<span id="status" class="status">HIDDEN</span>
<span id="mode" class="mode">Player movement</span>
</div>
<div class="meter">
<div id="meterFill"></div>
</div>
<div class="meter-label">
<span>Detection</span>
<span id="alertValue">0%</span>
</div>
<div class="live-grid">
<div class="live-cell">
<span>Distance</span>
<b id="distance">—</b>
</div>
<div class="live-cell">
<span>In 70° cone</span>
<b id="inCone">NO</b>
</div>
<div class="live-cell">
<span>Line of sight</span>
<b id="lineOfSight">—</b>
</div>
<div class="live-cell">
<span>Observer bearing</span>
<b id="bearing">—</b>
</div>
</div>
</section>
<details id="rules" class="panel" open>
<summary>Explicit sight rules</summary>
<ol class="rule-list">
<li>
Detection requires a center-to-center distance of
<strong>9 tiles or less</strong>.
</li>
<li>
The player must also be inside the observer's rotating
<strong>70° field of view</strong>.
</li>
<li>
The segment from observer to player is tested against every wall and
movable cover. Any solid intersection means <strong>blocked</strong>.
</li>
<li>
Wall and cover blocks are full-height and opaque. Detection therefore
<strong>cannot pass through a solid wall</strong>.
</li>
<li>
Detection rises at <strong>80% per second</strong> while visible and
falls at <strong>45% per second</strong> while hidden.
</li>
<li>
Orange blocks are movable cover. The floor wedge shows the observer's
actual range and is clipped by solid blocks.
</li>
</ol>
</details>
<div id="help" class="panel">
<kbd>WASD</kbd>/<kbd>↑↓←→</kbd> move ·
<kbd>E</kbd> grab/release cover ·
<kbd>R</kbd> reset ·
<kbd>C</kbd> camera ·
right-drag to orbit · wheel to zoom
</div>
<div id="toast"></div>
<div id="flash">
<div class="modal">
<div class="eyebrow">No harm was done</div>
<h2>Spotted!</h2>
<p>The observer is resetting the puzzle. Use cover and wait for the blind side.</p>
</div>
</div>
<div id="win">
<div class="modal">
<div class="eyebrow">Puzzle complete</div>
<h2>Unseen arrival</h2>
<p>You reached the beacon without the observer fully identifying you.</p>
<button id="restartButton">PLAY AGAIN</button>
</div>
</div>
<div id="touchControls">
<button class="up" data-dir="up" aria-label="Move up">▲</button>
<button class="left" data-dir="left" aria-label="Move left">◀</button>
<button class="down" data-dir="down" aria-label="Move down">▼</button>
<button class="right" data-dir="right" aria-label="Move right">▶</button>
<button class="grab" id="touchGrab">GRAB</button>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and level data
// -------------------------------------------------------------------------
const GRID = 16;
const VIEW_RANGE = 9;
const FIELD_OF_VIEW = THREE.MathUtils.degToRad(70);
const HALF_FOV = FIELD_OF_VIEW / 2;
const COS_HALF_FOV = Math.cos(HALF_FOV);
const ROTATION_SPEED = 0.28;
const DETECTION_RATE = 0.80;
const DECAY_RATE = 0.45;
const PLAYER_RADIUS = 0.25;
const START = { x: 2, z: 13 };
const GOAL = { x: 13, z: 2 };
const GUARD = { x: 12, z: 9 };
const INITIAL_GUARD_ANGLE = -Math.PI / 2;
const wallSet = new Set();
const wallCells = [];
function addWall(x, z) {
const key = `${x},${z}`;
if (!wallSet.has(key)) {
wallSet.add(key);
wallCells.push({ x, z });
}
}
// Outer shell.
for (let i = 0; i < GRID; i++) {
addWall(i, 0);
addWall(i, GRID - 1);
addWall(0, i);
addWall(GRID - 1, i);
}
// Interior solid voxel walls.
for (let z = 8; z <= 14; z++) addWall(5, z);
for (let x = 6; x <= 9; x++) addWall(x, 6);
for (let z = 2; z <= 6; z++) addWall(10, z);
for (let z = 10; z <= 14; z++) addWall(10, z);
for (let z = 12; z <= 14; z++) addWall(13, z);
const covers = [
{ name: "A", x: 7, z: 9, initialX: 7, initialZ: 9 },
{ name: "B", x: 8, z: 4, initialX: 8, initialZ: 4 },
{ name: "C", x: 12, z: 5, initialX: 12, initialZ: 5 }
];
const player = { x: START.x, z: START.z };
const guard = {
x: GUARD.x,
z: GUARD.z,
angle: INITIAL_GUARD_ANGLE
};
let selectedCover = null;
let detection = 0;
let gameTime = 0;
let caught = false;
let won = false;
let toastTimer = 0;
const keys = new Set();
// -------------------------------------------------------------------------
// Renderer, scene, and camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101a);
scene.fog = new THREE.Fog(0x07101a, 24, 46);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
document.body.prepend(renderer.domElement);
const cameraTarget = new THREE.Vector3(7.5, 0.25, 7.5);
const cameraState = {
azimuth: 0.72,
elevation: 0.72,
radius: 24
};
function updateCamera() {
const horizontal = cameraState.radius * Math.cos(cameraState.elevation);
camera.position.set(
cameraTarget.x + Math.sin(cameraState.azimuth) * horizontal,
cameraTarget.y + Math.sin(cameraState.elevation) * cameraState.radius,
cameraTarget.z + Math.cos(cameraState.azimuth) * horizontal
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xa9ddff, 0x14202b, 1.65);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d6, 2.3);
sun.position.set(-7, 17, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rim = new THREE.PointLight(0x52d9ff, 18, 28, 2);
rim.position.set(2, 7, 14);
scene.add(rim);
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
const world = new THREE.Group();
scene.add(world);
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const floorGeometry = new THREE.BoxGeometry(0.94, 0.16, 0.94);
const wallGeometry = new THREE.BoxGeometry(0.96, 1.5, 0.96);
const capGeometry = new THREE.BoxGeometry(0.98, 0.12, 0.98);
const floorMaterials = [
new THREE.MeshStandardMaterial({
color: 0x172637,
roughness: 0.92,
metalness: 0.04
}),
new THREE.MeshStandardMaterial({
color: 0x1b2c3d,
roughness: 0.92,
metalness: 0.04
})
];
const wallMaterials = [
new THREE.MeshStandardMaterial({
color: 0x41566b,
roughness: 0.8,
metalness: 0.08
}),
new THREE.MeshStandardMaterial({
color: 0x4b6177,
roughness: 0.8,
metalness: 0.08
}),
new THREE.MeshStandardMaterial({
color: 0x354a5f,
roughness: 0.8,
metalness: 0.08
})
];
const capMaterial = new THREE.MeshStandardMaterial({
color: 0x6b8297,
roughness: 0.75
});
for (let x = 0; x < GRID; x++) {
for (let z = 0; z < GRID; z++) {
const floor = new THREE.Mesh(
floorGeometry,
floorMaterials[(x + z) % 2]
);
floor.position.set(x, -0.08, z);
floor.receiveShadow = true;
world.add(floor);
}
}
for (let i = 0; i < wallCells.length; i++) {
const cell = wallCells[i];
const wall = new THREE.Mesh(
wallGeometry,
wallMaterials[i % wallMaterials.length]
);
wall.position.set(cell.x, 0.75, cell.z);
wall.castShadow = true;
wall.receiveShadow = true;
world.add(wall);
const cap = new THREE.Mesh(capGeometry, capMaterial);
cap.position.set(cell.x, 1.56, cell.z);
cap.castShadow = true;
cap.receiveShadow = true;
world.add(cap);
}
// Goal beacon, constructed from voxel pieces.
const goalGroup = new THREE.Group();
goalGroup.position.set(GOAL.x, 0, GOAL.z);
const goalMaterial = new THREE.MeshStandardMaterial({
color: 0x51e89b,
emissive: 0x1a8e59,
emissiveIntensity: 0.65,
roughness: 0.4
});
const goalDarkMaterial = new THREE.MeshStandardMaterial({
color: 0x123b32,
roughness: 0.7
});
const pad = new THREE.Mesh(
new THREE.BoxGeometry(0.9, 0.08, 0.9),
goalMaterial
);
pad.position.y = 0.04;
goalGroup.add(pad);
for (const x of [-0.36, 0.36]) {
for (const z of [-0.36, 0.36]) {
const pillar = new THREE.Mesh(boxGeometry, goalMaterial);
pillar.scale.set(0.18, 0.9, 0.18);
pillar.position.set(x, 0.49, z);
pillar.castShadow = true;
goalGroup.add(pillar);
}
}
const goalTop = new THREE.Mesh(boxGeometry, goalMaterial);
goalTop.scale.set(0.9, 0.18, 0.18);
goalTop.position.y = 0.94;
goalTop.castShadow = true;
goalGroup.add(goalTop);
const floatingGoal = new THREE.Mesh(boxGeometry, goalMaterial);
floatingGoal.scale.setScalar(0.24);
floatingGoal.position.y = 1.42;
floatingGoal.castShadow = true;
goalGroup.add(floatingGoal);
const goalRing = new THREE.Mesh(
new THREE.TorusGeometry(0.55, 0.045, 8, 32),
new THREE.MeshBasicMaterial({ color: 0x72f0a8 })
);
goalRing.rotation.x = Math.PI / 2;
goalRing.position.y = 0.055;
goalGroup.add(goalRing);
world.add(goalGroup);
// -------------------------------------------------------------------------
// Player and observer characters
// -------------------------------------------------------------------------
function createCharacter(bodyColor, accentColor, isGuard = false) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: bodyColor,
roughness: 0.65,
metalness: 0.05
});
const accentMaterial = new THREE.MeshStandardMaterial({
color: accentColor,
emissive: accentColor,
emissiveIntensity: isGuard ? 0.45 : 0.12,
roughness: 0.4
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x0b1420,
roughness: 0.75
});
const body = new THREE.Mesh(boxGeometry, bodyMaterial);
body.scale.set(0.54, 0.66, 0.54);
body.position.y = 0.46;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(boxGeometry, bodyMaterial);
head.scale.set(0.43, 0.4, 0.43);
head.position.y = 0.99;
head.castShadow = true;
group.add(head);
const visor = new THREE.Mesh(boxGeometry, accentMaterial);
visor.scale.set(0.34, 0.13, 0.075);
visor.position.set(0, 1.01, 0.245);
group.add(visor);
for (const x of [-0.15, 0.15]) {
const leg = new THREE.Mesh(boxGeometry, darkMaterial);
leg.scale.set(0.18, 0.28, 0.2);
leg.position.set(x, 0.14, 0);
leg.castShadow = true;
group.add(leg);
}
if (isGuard) {
const antenna = new THREE.Mesh(boxGeometry, accentMaterial);
antenna.scale.set(0.08, 0.24, 0.08);
antenna.position.y = 1.31;
group.add(antenna);
}
return group;
}
const playerMesh = createCharacter(0x3aa9ff, 0xb8f4ff);
playerMesh.position.set(player.x, 0, player.z);
world.add(playerMesh);
const guardMesh = createCharacter(0xffa93b, 0xff3c57, true);
guardMesh.position.set(guard.x, 0, guard.z);
world.add(guardMesh);
const guardLamp = new THREE.PointLight(0xff8b3c, 5, 5, 2);
guardLamp.position.set(0, 1.25, 0.35);
guardMesh.add(guardLamp);
// -------------------------------------------------------------------------
// Movable voxel covers
// -------------------------------------------------------------------------
const coverMaterial = new THREE.MeshStandardMaterial({
color: 0xf28b3c,
roughness: 0.68,
metalness: 0.05
});
const coverBandMaterial = new THREE.MeshStandardMaterial({
color: 0xffd08b,
emissive: 0x7a3500,
emissiveIntensity: 0.25,
roughness: 0.55
});
const coverPickMeshes = [];
for (const cover of covers) {
const group = new THREE.Group();
group.position.set(cover.x, 0, cover.z);
const main = new THREE.Mesh(boxGeometry, coverMaterial);
main.scale.set(0.88, 1.14, 0.88);
main.position.y = 0.57;
main.castShadow = true;
main.receiveShadow = true;
main.userData.coverIndex = covers.indexOf(cover);
group.add(main);
coverPickMeshes.push(main);
const band = new THREE.Mesh(boxGeometry, coverBandMaterial);
band.scale.set(0.92, 0.14, 0.92);
band.position.y = 0.78;
band.castShadow = true;
group.add(band);
const handle = new THREE.Mesh(boxGeometry, coverBandMaterial);
handle.scale.set(0.34, 0.07, 0.1);
handle.position.set(0, 1.17, 0);
group.add(handle);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1.02, 1.22, 1.02)),
new THREE.LineBasicMaterial({ color: 0x9df5ff })
);
outline.position.y = 0.61;
outline.visible = false;
group.add(outline);
cover.group = group;
cover.outline = outline;
world.add(group);
}
// -------------------------------------------------------------------------
// Vision wedge, clipped by every solid wall and cover
// -------------------------------------------------------------------------
const VISION_SAMPLES = 44;
const visionPositions = new Float32Array(
VISION_SAMPLES * 2 * 3
);
const visionGeometry = new THREE.BufferGeometry();
visionGeometry.setAttribute(
"position",
new THREE.BufferAttribute(visionPositions, 3)
);
const visionMaterial = new THREE.MeshBasicMaterial({
color: 0xffc45f,
transparent: true,
opacity: 0.13,
depthWrite: false,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: -1
});
const visionMesh = new THREE.Mesh(visionGeometry, visionMaterial);
visionMesh.frustumCulled = false;
world.add(visionMesh);
// -------------------------------------------------------------------------
// Explicit collision and occlusion rules
// -------------------------------------------------------------------------
function isWallCell(ix, iz) {
return wallSet.has(`${ix},${iz}`);
}
function coverAtCell(ix, iz, ignoredCover = null) {
return covers.find(
cover => cover !== ignoredCover && cover.x === ix && cover.z === iz
);
}
function isSolidCell(ix, iz, ignoredCover = null) {
return isWallCell(ix, iz) || Boolean(coverAtCell(ix, iz, ignoredCover));
}
function circleTouchesCell(cx, cz, ix, iz, radius) {
const closestX = THREE.MathUtils.clamp(cx, ix - 0.48, ix + 0.48);
const closestZ = THREE.MathUtils.clamp(cz, iz - 0.48, iz + 0.48);
const dx = cx - closestX;
const dz = cz - closestZ;
return dx * dx + dz * dz < radius * radius;
}
function canPlayerStand(x, z) {
const minX = Math.floor(x - PLAYER_RADIUS + 0.5);
const maxX = Math.floor(x + PLAYER_RADIUS + 0.5);
const minZ = Math.floor(z - PLAYER_RADIUS + 0.5);
const maxZ = Math.floor(z + PLAYER_RADIUS + 0.5);
for (let ix = minX; ix <= maxX; ix++) {
for (let iz = minZ; iz <= maxZ; iz++) {
if (
isSolidCell(ix, iz) &&
circleTouchesCell(x, z, ix, iz, PLAYER_RADIUS)
) {
return false;
}
}
}
// The observer is also physically solid.
const guardDistance = Math.hypot(
x - guard.x,
z - guard.z
);
if (guardDistance < 0.76) return false;
return true;
}
// Segment versus axis-aligned solid rectangle.
function segmentIntersectsRect(
ax,
az,
bx,
bz,
minX,
maxX,
minZ,
maxZ
) {
const dx = bx - ax;
const dz = bz - az;
let tMin = 0;
let tMax = 1;
if (Math.abs(dx) < 1e-8) {
if (ax < minX || ax > maxX) return false;
} else {
let t1 = (minX - ax) / dx;
let t2 = (maxX - ax) / dx;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) return false;
}
if (Math.abs(dz) < 1e-8) {
if (az < minZ || az > maxZ) return false;
} else {
let t1 = (minZ - az) / dz;
let t2 = (maxZ - az) / dz;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) return false;
}
return tMax >= 0 && tMin <= 1;
}
function segmentIsBlocked(ax, az, bx, bz) {
// Every full-height wall is an opaque occluder.
for (const wall of wallCells) {
if (
segmentIntersectsRect(
ax,
az,
bx,
bz,
wall.x - 0.48,
wall.x + 0.48,
wall.z - 0.48,
wall.z + 0.48
)
) {
return true;
}
}
// Every movable cover is also a full-height opaque occluder.
for (const cover of covers) {
if (
segmentIntersectsRect(
ax,
az,
bx,
bz,
cover.x - 0.45,
cover.x + 0.45,
cover.z - 0.45,
cover.z + 0.45
)
) {
return true;
}
}
return false;
}
function rayDistanceThroughSolids(x, z, dx, dz, maxDistance) {
// Used only to draw the clipped floor wedge. Detection itself uses the
// exact segment-versus-rectangle test above.
const step = 0.07;
for (let distance = step; distance <= maxDistance; distance += step) {
const px = x + dx * distance;
const pz = z + dz * distance;
const ix = Math.floor(px + 0.5);
const iz = Math.floor(pz + 0.5);
if (isSolidCell(ix, iz)) {
return Math.max(0, distance - step * 0.5);
}
}
return maxDistance;
}
function evaluateSight() {
const dx = player.x - guard.x;
const dz = player.z - guard.z;
const distance = Math.hypot(dx, dz);
const inRange = distance <= VIEW_RANGE;
let inCone = false;
if (distance > 0.0001 && inRange) {
const dot =
(dx * Math.cos(guard.angle) + dz * Math.sin(guard.angle)) /
distance;
inCone = dot >= COS_HALF_FOV;
}
const blocked =
inCone &&
segmentIsBlocked(guard.x, guard.z, player.x, player.z);
return {
distance,
inRange,
inCone,
blocked,
visible: inCone && !blocked
};
}
// -------------------------------------------------------------------------
// Interaction
// -------------------------------------------------------------------------
function showToast(message, duration = 3000) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), duration);
}
function selectCover(cover) {
if (!cover) return;
const distance = Math.hypot(
player.x - cover.x,
player.z - cover.z
);
if (distance > 1.7) {
showToast("Move closer to that orange cover before grabbing it.");
return;
}
selectedCover = cover;
for (const item of covers) {
item.outline.visible = item === selectedCover;
}
showToast(
`Cover ${cover.name} selected. Tap WASD/arrows to slide it one tile at a time.`
);
updateHUD(evaluateSight());
}
function releaseCover() {
if (!selectedCover) return;
const name = selectedCover.name;
selectedCover = null;
for (const item of covers) item.outline.visible = false;
showToast(`Cover ${name} released.`);
updateHUD(evaluateSight());
}
function toggleGrab(preferredCover = null) {
if (selectedCover) {
releaseCover();
return;
}
if (preferredCover) {
selectCover(preferredCover);
return;
}
let nearest = null;
let nearestDistance = Infinity;
for (const cover of covers) {
const distance = Math.hypot(
player.x - cover.x,
player.z - cover.z
);
if (distance < nearestDistance) {
nearestDistance = distance;
nearest = cover;
}
}
if (nearest && nearestDistance <= 1.7) {
selectCover(nearest);
} else {
showToast("No cover within reach. Walk closer to an orange block.");
}
}
function moveSelectedCover(dx, dz) {
if (!selectedCover || caught || won) return;
const cover = selectedCover;
const targetX = cover.x + dx;
const targetZ = cover.z + dz;
if (
targetX < 1 ||
targetX > GRID - 2 ||
targetZ < 1 ||
targetZ > GRID - 2 ||
isWallCell(targetX, targetZ) ||
coverAtCell(targetX, targetZ, cover) ||
(targetX === player.x && targetZ === player.z)
) {
showToast("That cover cannot slide there.");
return;
}
cover.x = targetX;
cover.z = targetZ;
}
function directionFromKey(code) {
switch (code) {
case "KeyW":
case "ArrowUp":
return { dx: 0, dz: -1 };
case "KeyS":
case "ArrowDown":
return { dx: 0, dz: 1 };
case "KeyA":
case "ArrowLeft":
return { dx: -1, dz: 0 };
case "KeyD":
case "ArrowRight":
return { dx: 1, dz: 0 };
default:
return null;
}
}
function resetGame(message = "") {
player.x = START.x;
player.z = START.z;
for (const cover of covers) {
cover.x = cover.initialX;
cover.z = cover.initialZ;
cover.group.position.set(cover.x, 0, cover.z);
cover.outline.visible = false;
}
selectedCover = null;
detection = 0;
gameTime = 0;
caught = false;
won = false;
guard.angle = INITIAL_GUARD_ANGLE;
playerMesh.position.set(player.x, 0, player.z);
guardMesh.position.set(guard.x, 0, guard.z);
document.getElementById("flash").classList.remove("show");
document.getElementById("win").classList.remove("show");
if (message) showToast(message);
updateHUD(evaluateSight());
}
function triggerCaught() {
if (caught || won) return;
caught = true;
detection = 1;
document.getElementById("flash").classList.add("show");
setTimeout(() => {
resetGame();
showToast(
"Reset. Break the observer's sightline or use its blind side.",
3500
);
}, 900);
}
function triggerWin() {
if (won || caught) return;
won = true;
detection = 0;
document.getElementById("win").classList.add("show");
}
// -------------------------------------------------------------------------
// Keyboard and pointer controls
// -------------------------------------------------------------------------
window.addEventListener("keydown", event => {
if (
["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Space"].includes(
event.code
)
) {
event.preventDefault();
}
const direction = directionFromKey(event.code);
if (direction) {
if (selectedCover) {
// Each press slides exactly one tile.
if (!event.repeat) moveSelectedCover(direction.dx, direction.dz);
} else {
keys.add(event.code);
}
return;
}
if (event.code === "KeyE" && !event.repeat) {
toggleGrab();
}
if (event.code === "KeyR" && !event.repeat) {
resetGame("Puzzle reset.");
}
if (event.code === "KeyC" && !event.repeat) {
cameraState.azimuth = 0.72;
cameraState.elevation = 0.72;
cameraState.radius = 24;
}
});
window.addEventListener("keyup", event => {
keys.delete(event.code);
});
window.addEventListener("blur", () => keys.clear());
// Custom camera controls: no addons or examples modules.
let draggingCamera = false;
let pointerMoved = false;
let lastPointerX = 0;
let lastPointerY = 0;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
pointerMoved = false;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (event.button === 2) {
draggingCamera = true;
renderer.domElement.setPointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointermove", event => {
if (!draggingCamera) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
if (Math.abs(dx) + Math.abs(dy) > 1) pointerMoved = true;
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.004,
0.35,
1.2
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", event => {
draggingCamera = false;
if (
event.button === 0 &&
!pointerMoved &&
!caught &&
!won
) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(coverPickMeshes, false);
if (hits.length) {
const index = hits[0].object.userData.coverIndex;
toggleGrab(covers[index]);
}
}
});
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
15,
34
);
},
{ passive: false }
);
document.getElementById("restartButton").addEventListener(
"click",
() => resetGame("New attempt. The observer has reset its facing.")
);
document.getElementById("touchGrab").addEventListener(
"click",
() => toggleGrab()
);
const touchDirectionCodes = {
up: "KeyW",
down: "KeyS",
left: "KeyA",
right: "KeyD"
};
for (const button of document.querySelectorAll("[data-dir]")) {
const code = touchDirectionCodes[button.dataset.dir];
button.addEventListener("pointerdown", event => {
event.preventDefault();
const direction = directionFromKey(code);
if (selectedCover) {
moveSelectedCover(direction.dx, direction.dz);
} else {
keys.add(code);
}
button.setPointerCapture(event.pointerId);
});
const release = () => keys.delete(code);
button.addEventListener("pointerup", release);
button.addEventListener("pointercancel", release);
}
// -------------------------------------------------------------------------
// Simulation
// -------------------------------------------------------------------------
function updatePlayer(delta) {
let dx = 0;
let dz = 0;
if (keys.has("KeyA") || keys.has("ArrowLeft")) dx--;
if (keys.has("KeyD") || keys.has("ArrowRight")) dx++;
if (keys.has("KeyW") || keys.has("ArrowUp")) dz--;
if (keys.has("KeyS") || keys.has("ArrowDown")) dz++;
if (dx === 0 && dz === 0) return;
const length = Math.hypot(dx, dz);
dx /= length;
dz /= length;
const speed = 3.25;
const stepX = dx * speed * delta;
const stepZ = dz * speed * delta;
if (canPlayerStand(player.x + stepX, player.z)) {
player.x += stepX;
}
if (canPlayerStand(player.x, player.z + stepZ)) {
player.z += stepZ;
}
playerMesh.rotation.y = Math.atan2(dx, dz);
}
function updateVisionWedge() {
let writeIndex = 0;
for (let i = 0; i < VISION_SAMPLES; i++) {
const t = i / (VISION_SAMPLES - 1);
const angle = guard.angle - HALF_FOV + t * FIELD_OF_VIEW;
const dx = Math.cos(angle);
const dz = Math.sin(angle);
const distance = rayDistanceThroughSolids(
guard.x,
guard.z,
dx,
dz,
VIEW_RANGE
);
visionPositions[writeIndex++] = guard.x;
visionPositions[writeIndex++] = 0.035;
visionPositions[writeIndex++] = guard.z;
visionPositions[writeIndex++] = guard.x + dx * distance;
visionPositions[writeIndex++] = 0.035;
visionPositions[writeIndex++] = guard.z + dz * distance;
}
visionGeometry.attributes.position.needsUpdate = true;
visionGeometry.computeBoundingSphere();
}
function updateHUD(sight) {
const status = document.getElementById("status");
const mode = document.getElementById("mode");
const meterFill = document.getElementById("meterFill");
const alertValue = document.getElementById("alertValue");
status.textContent = sight.visible ? "VISIBLE" : "HIDDEN";
status.classList.toggle("visible", sight.visible);
mode.textContent = selectedCover
? `Moving cover ${selectedCover.name}`
: "Player movement";
meterFill.style.width = `${Math.round(detection * 100)}%`;
alertValue.textContent = `${Math.round(detection * 100)}%`;
document.getElementById("distance").textContent =
`${sight.distance.toFixed(1)} / ${VIEW_RANGE}`;
document.getElementById("inCone").textContent =
sight.inCone ? "YES" : "NO";
document.getElementById("lineOfSight").textContent =
!sight.inCone ? "—" : sight.blocked ? "BLOCKED" : "CLEAR";
const bearing =
((guard.angle * 180 / Math.PI) % 360 + 360) % 360;
document.getElementById("bearing").textContent =
`${Math.round(bearing)}°`;
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.fov = innerWidth < 720 ? 55 : 42;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
const clock = new THREE.Clock();
let hudTimer = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (!caught && !won) {
gameTime += delta;
guard.angle = INITIAL_GUARD_ANGLE + gameTime * ROTATION_SPEED;
updatePlayer(delta);
const sight = evaluateSight();
if (sight.visible) {
detection += DETECTION_RATE * delta;
} else {
detection -= DECAY_RATE * delta;
}
detection = THREE.MathUtils.clamp(detection, 0, 1);
if (detection >= 1) {
triggerCaught();
}
const goalDistance = Math.hypot(
player.x - GOAL.x,
player.z - GOAL.z
);
if (goalDistance < 0.58) {
triggerWin();
}
hudTimer -= delta;
if (hudTimer <= 0) {
updateHUD(sight);
hudTimer = 0.08;
}
visionMaterial.color.setHex(
sight.visible ? 0xff526d : 0xffc45f
);
visionMaterial.opacity = sight.visible ? 0.19 : 0.13;
}
// Smooth visual movement while keeping logical collision positions exact.
playerMesh.position.x = THREE.MathUtils.lerp(
playerMesh.position.x,
player.x,
1 - Math.exp(-18 * delta)
);
playerMesh.position.z = THREE.MathUtils.lerp(
playerMesh.position.z,
player.z,
1 - Math.exp(-18 * delta)
);
for (const cover of covers) {
cover.group.position.x = THREE.MathUtils.lerp(
cover.group.position.x,
cover.x,
1 - Math.exp(-14 * delta)
);
cover.group.position.z = THREE.MathUtils.lerp(
cover.group.position.z,
cover.z,
1 - Math.exp(-14 * delta)
);
}
// Local character forward is +Z; convert the world X/Z angle accordingly.
guardMesh.rotation.y = Math.PI / 2 - guard.angle;
floatingGoal.rotation.y += delta * 0.9;
floatingGoal.position.y = 1.42 + Math.sin(gameTime * 2) * 0.08;
goalRing.material.opacity = 0.65 + Math.sin(gameTime * 3) * 0.2;
goalRing.material.transparent = true;
updateVisionWedge();
updateCamera();
renderer.render(scene, camera);
}
resetGame();
showToast(
"Reach the green beacon. Orange blocks are opaque movable cover.",
4200
);
animate();
</script>
</body>
</html>
```