Prompt specification
Build or customize the Three.js 3D scene "Corner Turn With a Movable Crate" 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: Corner Turn With a Movable Crate
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/corner-turn-with-a-movable-crate-x3458
Scene Description Prompt:
Push a crate around a low-poly corridor corner, showing occupied cells and separate walking and pushing rules. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (corner-turn-with-a-movable-crate-x3458):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Corridor Crate — Walking and Pushing Rules</title>
<style>
:root {
--ink: #20313d;
--muted: #647784;
--panel: rgba(250, 253, 253, 0.92);
--border: rgba(37, 59, 72, 0.14);
--cyan: #2bc8d8;
--amber: #f3a83b;
--coral: #e76b62;
--green: #49b979;
--blue: #548be8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce7e9;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 14px 38px rgba(37, 59, 72, 0.13);
backdrop-filter: blur(12px);
pointer-events: none;
}
.brand {
top: 18px;
left: 18px;
width: 280px;
padding: 16px 17px;
}
.eyebrow {
margin-bottom: 4px;
color: #4b6876;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 21px;
line-height: 1.15;
letter-spacing: -0.025em;
}
.subtitle {
margin: 8px 0 13px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.legend {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 7px 12px;
font-size: 11px;
font-weight: 700;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.12);
}
.free { background: #d6e0df; }
.player { background: var(--cyan); }
.crate { background: var(--amber); }
.wall { background: var(--coral); }
.goal { background: var(--green); }
.rules {
top: 18px;
right: 18px;
width: 302px;
padding: 16px 17px;
}
.rule {
display: grid;
grid-template-columns: 30px 1fr;
gap: 10px;
margin-top: 13px;
}
.rule-number {
display: grid;
width: 28px;
height: 28px;
place-items: center;
border-radius: 9px;
color: white;
background: var(--blue);
font-size: 12px;
font-weight: 900;
}
.rule:nth-of-type(3) .rule-number {
background: var(--amber);
color: #513209;
}
.rule strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
}
.rule p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.formula {
margin-top: 12px;
padding: 9px 10px;
border: 1px solid rgba(84, 139, 232, 0.18);
border-radius: 9px;
background: rgba(84, 139, 232, 0.07);
color: #3c5871;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
text-align: center;
}
.controls-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 14px;
pointer-events: auto;
}
button {
border: 1px solid rgba(37, 59, 72, 0.16);
border-radius: 9px;
padding: 8px 10px;
background: white;
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease;
}
button:hover {
transform: translateY(-1px);
background: #eef4f5;
}
button:active {
transform: translateY(0);
}
button[aria-pressed="true"] {
border-color: rgba(231, 107, 98, 0.35);
background: rgba(231, 107, 98, 0.1);
}
.compass {
position: absolute;
right: 16px;
bottom: 15px;
display: grid;
width: 44px;
height: 44px;
place-items: center;
border: 1px solid rgba(37, 59, 72, 0.13);
border-radius: 50%;
background: rgba(255, 255, 255, 0.72);
color: #47606e;
font-size: 10px;
font-weight: 900;
}
#compassNeedle {
display: block;
transform-origin: 50% 50%;
}
.status {
position: fixed;
z-index: 10;
bottom: 18px;
left: 18px;
max-width: min(510px, calc(100vw - 155px));
padding: 13px 15px;
border-left: 4px solid #81939d;
pointer-events: none;
transition: border-color 150ms ease;
}
.status[data-tone="good"] { border-left-color: var(--green); }
.status[data-tone="warn"] { border-left-color: var(--amber); }
.status[data-tone="bad"] { border-left-color: var(--coral); }
.status-label {
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#statusText {
font-size: 12px;
font-weight: 700;
line-height: 1.4;
}
#actionHint {
position: fixed;
z-index: 9;
top: 19px;
left: 50%;
max-width: 430px;
padding: 9px 13px;
transform: translateX(-50%);
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.86);
box-shadow: 0 8px 22px rgba(37, 59, 72, 0.09);
color: #4c6572;
font-size: 11px;
font-weight: 750;
text-align: center;
pointer-events: none;
}
.dpad {
position: fixed;
z-index: 12;
right: 18px;
bottom: 82px;
display: grid;
grid-template-columns: repeat(3, 38px);
grid-template-rows: repeat(3, 38px);
gap: 4px;
}
.dpad button {
display: grid;
padding: 0;
place-items: center;
border-radius: 10px;
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 5px 14px rgba(37, 59, 72, 0.1);
font-size: 18px;
}
.dpad .up { grid-column: 2; grid-row: 1; }
.dpad .left { grid-column: 1; grid-row: 2; }
.dpad .right { grid-column: 3; grid-row: 2; }
.dpad .down { grid-column: 2; grid-row: 3; }
.camera-note {
margin-top: 11px;
color: #80909a;
font-size: 10px;
line-height: 1.4;
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: #dce7e9;
color: #526a77;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 800px) {
.brand {
width: 230px;
}
.rules {
top: auto;
bottom: 148px;
right: 12px;
width: 260px;
}
.brand {
top: 12px;
left: 12px;
}
.status {
right: 12px;
bottom: 12px;
left: 12px;
max-width: none;
}
#actionHint {
display: none;
}
.dpad {
right: 12px;
bottom: 151px;
}
}
@media (max-width: 560px) {
.rules {
display: none;
}
.brand {
width: calc(100vw - 24px);
}
.legend {
grid-template-columns: repeat(3, 1fr);
}
.subtitle {
margin-bottom: 9px;
}
}
</style>
</head>
<body>
<div id="loading">Building corridor…</div>
<section class="panel brand">
<div class="eyebrow">Grid Logistics Demo</div>
<h1>Push the crate around the corner</h1>
<p class="subtitle">
Move the amber crate from the upper corridor to the green goal tile.
</p>
<div class="legend">
<div class="legend-item"><span class="swatch free"></span>Free cell</div>
<div class="legend-item"><span class="swatch player"></span>Player</div>
<div class="legend-item"><span class="swatch crate"></span>Crate</div>
<div class="legend-item"><span class="swatch wall"></span>Wall / occupied</div>
<div class="legend-item"><span class="swatch goal"></span>Goal</div>
</div>
<div class="controls-row">
<button id="toggleOccupancy" aria-pressed="true">Occupied cells: ON</button>
<button id="resetButton">Reset</button>
</div>
<div class="camera-note">
WASD / arrows use grid directions. Click a tile to walk there, or click
the crate to approach and push it. Drag to orbit; wheel to zoom.
</div>
<div class="compass" title="Grid north">
<span id="compassNeedle">↑ N</span>
</div>
</section>
<section class="panel rules">
<div class="eyebrow">Two independent rules</div>
<div class="rule">
<div class="rule-number">1</div>
<div>
<strong>Walking</strong>
<p>The player may enter only a free, walkable cell.</p>
</div>
</div>
<div class="rule">
<div class="rule-number">2</div>
<div>
<strong>Pushing</strong>
<p>
The player may enter the crate’s cell only if the cell directly
beyond it is free and walkable.
</p>
</div>
</div>
<div class="formula">P → C → free = P moves into C, C moves forward</div>
</section>
<div id="actionHint">Click a neighboring tile to walk, or click the crate to push.</div>
<section id="statusCard" class="panel status" data-tone="neutral">
<div class="status-label">Current state</div>
<div id="statusText">Push the crate around the bend and onto the green goal.</div>
</section>
<div class="dpad" aria-label="Grid movement controls">
<button class="up" data-dx="0" data-dz="-1" title="North">↑</button>
<button class="left" data-dx="-1" data-dz="0" title="West">←</button>
<button class="right" data-dx="1" data-dz="0" title="East">→</button>
<button class="down" data-dx="0" data-dz="1" title="South">↓</button>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Configuration
// ------------------------------------------------------------
const COLS = 10;
const ROWS = 8;
const CELL = 1;
const START_PLAYER = { x: 2, z: 1 };
const START_CRATE = { x: 2, z: 2 };
const GOAL = { x: 7, z: 5 };
const walkable = new Set();
// Two-cell-wide vertical leg.
for (let z = 1; z <= 6; z++) {
walkable.add(`${1},${z}`);
walkable.add(`${2},${z}`);
}
// Two-cell-wide horizontal leg.
for (let x = 1; x <= 8; x++) {
walkable.add(`${x},${5}`);
walkable.add(`${x},${6}`);
}
const key = (x, z) => `${x},${z}`;
const isWalkable = (x, z) => walkable.has(key(x, z));
const inBounds = (x, z) => x >= 0 && x < COLS && z >= 0 && z < ROWS;
const worldX = x => (x - (COLS - 1) / 2) * CELL;
const worldZ = z => (z - (ROWS - 1) / 2) * CELL;
const playerCell = { ...START_PLAYER };
const crateCell = { ...START_CRATE };
let animation = null;
let autoPath = [];
let autoPush = null;
let solved = false;
let occupancyVisible = true;
let crateFlash = 0;
const statusCard = document.querySelector("#statusCard");
const statusText = document.querySelector("#statusText");
const actionHint = document.querySelector("#actionHint");
const occupancyButton = document.querySelector("#toggleOccupancy");
const resetButton = document.querySelector("#resetButton");
const compassNeedle = document.querySelector("#compassNeedle");
function setStatus(text, tone = "neutral") {
statusText.textContent = text;
statusCard.dataset.tone = tone;
}
// ------------------------------------------------------------
// Renderer, scene, camera
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce7e9);
scene.fog = new THREE.Fog(0xdce7e9, 24, 46);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
document.body.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-10, 10, 7, -7, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.1, 0);
let cameraYaw = 0.12;
let cameraPolar = 0.88;
function updateCamera() {
const radius = 24;
camera.position.set(
cameraTarget.x + radius * Math.sin(cameraPolar) * Math.sin(cameraYaw),
cameraTarget.y + radius * Math.cos(cameraPolar),
cameraTarget.z + radius * Math.sin(cameraPolar) * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
const center = new THREE.Vector3(0, 0.1, 0).project(camera);
const north = new THREE.Vector3(0, 0.1, -1).project(camera);
const sx = north.x - center.x;
const sy = -(north.y - center.y);
const angle = Math.atan2(sx, -sy);
compassNeedle.style.transform = `rotate(${angle}rad)`;
}
function resize() {
const aspect = window.innerWidth / window.innerHeight;
const viewHeight = Math.max(10.5, 13.5 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
updateCamera();
resize();
const hemi = new THREE.HemisphereLight(0xeaf7ff, 0x71808a, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d7, 3.1);
sun.position.set(-7, 13, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9ad9ef, 1.1);
fill.position.set(9, 5, -7);
scene.add(fill);
// ------------------------------------------------------------
// Board and cells
// ------------------------------------------------------------
const floorMaterials = [
new THREE.MeshStandardMaterial({
color: 0xd4dfdc,
roughness: 0.93,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0xc6d3d1,
roughness: 0.95,
flatShading: true
})
];
const wallMaterials = [
new THREE.MeshStandardMaterial({
color: 0x667985,
roughness: 0.95,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x738691,
roughness: 0.95,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x596d79,
roughness: 0.95,
flatShading: true
})
];
const occupancyGroup = new THREE.Group();
scene.add(occupancyGroup);
const pickables = [];
const wallHeights = new Map();
const boardBase = new THREE.Mesh(
new THREE.BoxGeometry(COLS + 0.35, 0.32, ROWS + 0.35),
new THREE.MeshStandardMaterial({
color: 0x50636e,
roughness: 0.95,
flatShading: true
})
);
boardBase.position.y = -0.18;
boardBase.receiveShadow = true;
scene.add(boardBase);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0xd4e0e1,
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.36;
ground.receiveShadow = true;
scene.add(ground);
for (let z = 0; z < ROWS; z++) {
for (let x = 0; x < COLS; x++) {
if (isWalkable(x, z)) {
const floor = new THREE.Mesh(
new THREE.BoxGeometry(0.97, 0.08, 0.97),
floorMaterials[(x + z) % 2]
);
floor.position.set(worldX(x), 0, worldZ(z));
floor.receiveShadow = true;
floor.userData.cell = { x, z };
floor.userData.pickType = "floor";
scene.add(floor);
pickables.push(floor);
} else {
const h = 0.48 + ((x * 7 + z * 11) % 5) * 0.065;
wallHeights.set(key(x, z), h);
const wall = new THREE.Mesh(
new THREE.BoxGeometry(0.98, h, 0.98),
wallMaterials[(x + z) % wallMaterials.length]
);
wall.position.set(worldX(x), h / 2 - 0.01, worldZ(z));
wall.castShadow = true;
wall.receiveShadow = true;
wall.userData.cell = { x, z };
wall.userData.pickType = "wall";
scene.add(wall);
pickables.push(wall);
const occupied = new THREE.Mesh(
new THREE.PlaneGeometry(0.82, 0.82),
new THREE.MeshBasicMaterial({
color: 0xe76b62,
transparent: true,
opacity: 0.16,
depthWrite: false,
side: THREE.DoubleSide
})
);
occupied.rotation.x = -Math.PI / 2;
occupied.position.set(worldX(x), h + 0.012, worldZ(z));
occupied.renderOrder = 2;
occupancyGroup.add(occupied);
}
}
}
// Fine grid lines over the walkable corridor.
const gridVertices = [];
for (let x = 0; x <= COLS; x++) {
gridVertices.push(
worldX(x) - 0.5, 0.045, -ROWS / 2,
worldX(x) - 0.5, 0.045, ROWS / 2
);
}
for (let z = 0; z <= ROWS; z++) {
gridVertices.push(
-COLS / 2, 0.045, worldZ(z) - 0.5,
COLS / 2, 0.045, worldZ(z) - 0.5
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x657d84,
transparent: true,
opacity: 0.22
})
);
scene.add(grid);
// ------------------------------------------------------------
// Goal
// ------------------------------------------------------------
const goalTile = new THREE.Mesh(
new THREE.PlaneGeometry(0.84, 0.84),
new THREE.MeshBasicMaterial({
color: 0x49b979,
transparent: true,
opacity: 0.3,
depthWrite: false,
side: THREE.DoubleSide
})
);
goalTile.rotation.x = -Math.PI / 2;
goalTile.position.set(worldX(GOAL.x), 0.052, worldZ(GOAL.z));
scene.add(goalTile);
const goalRing = new THREE.Mesh(
new THREE.TorusGeometry(0.23, 0.045, 4, 18),
new THREE.MeshBasicMaterial({
color: 0x49b979,
transparent: true,
opacity: 0.92
})
);
goalRing.rotation.x = Math.PI / 2;
goalRing.position.set(worldX(GOAL.x), 0.085, worldZ(GOAL.z));
scene.add(goalRing);
// ------------------------------------------------------------
// Crate
// ------------------------------------------------------------
const crateGroup = new THREE.Group();
scene.add(crateGroup);
const crateMaterial = new THREE.MeshStandardMaterial({
color: 0xd99332,
roughness: 0.78,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const crateBody = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.72, 0.72),
crateMaterial
);
crateBody.position.y = 0.38;
crateBody.castShadow = true;
crateBody.receiveShadow = true;
crateBody.userData.cell = crateCell;
crateBody.userData.pickType = "crate";
crateGroup.add(crateBody);
pickables.push(crateBody);
const crateEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(crateBody.geometry),
new THREE.LineBasicMaterial({ color: 0x754719 })
);
crateEdges.position.copy(crateBody.position);
crateGroup.add(crateEdges);
const slatMaterial = new THREE.MeshStandardMaterial({
color: 0xb87125,
roughness: 0.88,
flatShading: true
});
for (const offset of [-0.24, 0, 0.24]) {
for (const face of [-0.37, 0.37]) {
const slat = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.75, 0.045),
slatMaterial
);
slat.position.set(offset, 0.38, face);
slat.castShadow = true;
crateGroup.add(slat);
}
}
for (const offset of [-0.24, 0, 0.24]) {
for (const face of [-0.37, 0.37]) {
const slat = new THREE.Mesh(
new THREE.BoxGeometry(0.045, 0.75, 0.075),
slatMaterial
);
slat.position.set(face, 0.38, offset);
slat.castShadow = true;
crateGroup.add(slat);
}
}
const crateOccupancy = new THREE.Mesh(
new THREE.PlaneGeometry(0.86, 0.86),
new THREE.MeshBasicMaterial({
color: 0xf3a83b,
transparent: true,
opacity: 0.36,
depthWrite: false,
side: THREE.DoubleSide
})
);
crateOccupancy.rotation.x = -Math.PI / 2;
occupancyGroup.add(crateOccupancy);
// ------------------------------------------------------------
// Low-poly player
// ------------------------------------------------------------
const playerGroup = new THREE.Group();
scene.add(playerGroup);
const playerBodyMaterial = new THREE.MeshStandardMaterial({
color: 0x2bc8d8,
roughness: 0.72,
flatShading: true
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x294b59,
roughness: 0.9,
flatShading: true
});
const skinMaterial = new THREE.MeshStandardMaterial({
color: 0xf1c49f,
roughness: 0.9,
flatShading: true
});
for (const x of [-0.11, 0.11]) {
const leg = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.25, 0.16),
darkMaterial
);
leg.position.set(x, 0.13, 0);
leg.castShadow = true;
playerGroup.add(leg);
}
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.19, 0.25, 0.4, 5),
playerBodyMaterial
);
torso.position.y = 0.45;
torso.castShadow = true;
playerGroup.add(torso);
const head = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.18, 0),
skinMaterial
);
head.position.y = 0.79;
head.castShadow = true;
playerGroup.add(head);
const nose = new THREE.Mesh(
new THREE.ConeGeometry(0.065, 0.16, 4),
skinMaterial
);
nose.rotation.x = Math.PI / 2;
nose.position.set(0, 0.78, 0.23);
playerGroup.add(nose);
const playerOccupancy = new THREE.Mesh(
new THREE.PlaneGeometry(0.83, 0.83),
new THREE.MeshBasicMaterial({
color: 0x2bc8d8,
transparent: true,
opacity: 0.31,
depthWrite: false,
side: THREE.DoubleSide
})
);
playerOccupancy.rotation.x = -Math.PI / 2;
occupancyGroup.add(playerOccupancy);
// ------------------------------------------------------------
// Hover marker and push-direction arrow
// ------------------------------------------------------------
const hoverGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.44, 0, -0.44),
new THREE.Vector3(0.44, 0, -0.44),
new THREE.Vector3(0.44, 0, 0.44),
new THREE.Vector3(-0.44, 0, 0.44)
]);
const hoverRing = new THREE.LineLoop(
hoverGeometry,
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
hoverRing.visible = false;
hoverRing.renderOrder = 20;
scene.add(hoverRing);
const pushArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 0, 1),
new THREE.Vector3(),
0.9,
0x49b979,
0.23,
0.16
);
pushArrow.visible = false;
pushArrow.line.material.depthTest = false;
pushArrow.cone.material.depthTest = false;
scene.add(pushArrow);
// ------------------------------------------------------------
// Game rules and movement
// ------------------------------------------------------------
function sameCell(a, b) {
return a.x === b.x && a.z === b.z;
}
function isCrateCell(x, z) {
return crateCell.x === x && crateCell.z === z;
}
function isPlayerCell(x, z) {
return playerCell.x === x && playerCell.z === z;
}
function crateDestinationIsFree(x, z) {
return inBounds(x, z) &&
isWalkable(x, z) &&
!isCrateCell(x, z) &&
!isPlayerCell(x, z);
}
function beginAnimation(playerFrom, playerTo, crateFrom = null, crateTo = null) {
animation = {
elapsed: 0,
duration: 0.18,
playerFrom: new THREE.Vector3(
worldX(playerFrom.x), 0.04, worldZ(playerFrom.z)
),
playerTo: new THREE.Vector3(
worldX(playerTo.x), 0.04, worldZ(playerTo.z)
),
crateFrom: crateFrom
? new THREE.Vector3(worldX(crateFrom.x), 0.04, worldZ(crateFrom.z))
: null,
crateTo: crateTo
? new THREE.Vector3(worldX(crateTo.x), 0.04, worldZ(crateTo.z))
: null
};
}
function attemptMove(dx, dz, quiet = false) {
if (animation) return false;
const target = {
x: playerCell.x + dx,
z: playerCell.z + dz
};
if (!inBounds(target.x, target.z) || !isWalkable(target.x, target.z)) {
if (!quiet) {
setStatus("Walk blocked: that cell is outside the corridor.", "bad");
}
return false;
}
if (isCrateCell(target.x, target.z)) {
const destination = {
x: crateCell.x + dx,
z: crateCell.z + dz
};
// The pushing rule is deliberately separate from walking:
// the cell beyond the crate must also be free.
if (!crateDestinationIsFree(destination.x, destination.z)) {
crateFlash = 1;
if (!quiet) {
setStatus(
"Push blocked: the cell directly beyond the crate is occupied.",
"bad"
);
}
return false;
}
const playerFrom = { ...playerCell };
const crateFrom = { ...crateCell };
playerCell.x = crateFrom.x;
playerCell.z = crateFrom.z;
crateCell.x = destination.x;
crateCell.z = destination.z;
crateBody.userData.cell = { ...crateCell };
beginAnimation(playerFrom, playerCell, crateFrom, crateCell);
if (!quiet) {
if (sameCell(crateCell, GOAL)) {
setStatus("Pushing the crate onto the goal…", "good");
} else if (crateCell.x === 2 && crateCell.z === 5) {
setStatus(
"The crate reached the bend. Move to its west side, then push east.",
"warn"
);
} else {
setStatus(
`Push: the crate moved to column ${crateCell.x + 1}, row ${crateCell.z + 1}.`,
"good"
);
}
}
return true;
}
if (isPlayerCell(target.x, target.z)) {
return false;
}
const playerFrom = { ...playerCell };
playerCell.x = target.x;
playerCell.z = target.z;
beginAnimation(playerFrom, playerCell);
if (!quiet) {
setStatus("Walk: the player moved one cell.", "neutral");
}
return true;
}
// Breadth-first pathfinding for click-to-walk and crate approach.
function findPath(start, goal) {
if (!isWalkable(goal.x, goal.z) || isCrateCell(goal.x, goal.z)) {
return null;
}
const queue = [{ ...start }];
const visited = new Set([key(start.x, start.z)]);
const cameFrom = new Map();
while (queue.length) {
const current = queue.shift();
if (sameCell(current, goal)) {
const path = [];
let cursor = goal;
while (!sameCell(cursor, start)) {
path.push({ ...cursor });
cursor = cameFrom.get(key(cursor.x, cursor.z));
}
return path.reverse();
}
const neighbors = [
{ x: current.x + 1, z: current.z },
{ x: current.x - 1, z: current.z },
{ x: current.x, z: current.z + 1 },
{ x: current.x, z: current.z - 1 }
];
for (const next of neighbors) {
const nextKey = key(next.x, next.z);
if (
!visited.has(nextKey) &&
inBounds(next.x, next.z) &&
isWalkable(next.x, next.z) &&
!isCrateCell(next.x, next.z)
) {
visited.add(nextKey);
cameFrom.set(nextKey, current);
queue.push(next);
}
}
}
return null;
}
function planApproachToCrate() {
const neighbors = [
{ x: crateCell.x + 1, z: crateCell.z },
{ x: crateCell.x - 1, z: crateCell.z },
{ x: crateCell.x, z: crateCell.z + 1 },
{ x: crateCell.x, z: crateCell.z - 1 }
];
let best = null;
for (const neighbor of neighbors) {
if (!inBounds(neighbor.x, neighbor.z)) continue;
if (!isWalkable(neighbor.x, neighbor.z)) continue;
if (isCrateCell(neighbor.x, neighbor.z)) continue;
const path = findPath(playerCell, neighbor);
if (path && (!best || path.length < best.path.length)) {
best = { path, neighbor };
}
}
if (!best) {
setStatus("The crate cannot be approached from a free neighboring cell.", "bad");
return;
}
autoPath = best.path;
autoPush = {
dx: crateCell.x - best.neighbor.x,
dz: crateCell.z - best.neighbor.z
};
setStatus("Approaching the crate to push it…", "neutral");
}
function stepAutomaticMovement() {
if (animation) return;
if (autoPath.length) {
const next = autoPath.shift();
const dx = next.x - playerCell.x;
const dz = next.z - playerCell.z;
if (!attemptMove(dx, dz, true)) {
autoPath = [];
autoPush = null;
setStatus("The walking path was interrupted.", "warn");
}
return;
}
if (autoPush) {
const push = autoPush;
autoPush = null;
attemptMove(push.dx, push.dz, false);
}
}
function clearAutomaticMovement() {
autoPath = [];
autoPush = null;
}
// ------------------------------------------------------------
// Picking, hover feedback, and click actions
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pick(event) {
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(pickables, false);
return hits.length ? hits[0].object : null;
}
function adjacentDirection(from, to) {
const dx = to.x - from.x;
const dz = to.z - from.z;
if (Math.abs(dx) + Math.abs(dz) !== 1) return null;
return { dx, dz };
}
function evaluateTarget(cell, pickType) {
if (pickType === "wall") {
return {
type: "blocked",
color: 0xe76b62,
text: "BLOCKED · this is a wall / occupied cell."
};
}
if (pickType === "crate") {
const direction = adjacentDirection(playerCell, crateCell);
if (!direction) {
return {
type: "approach",
color: 0x548be8,
text: "CLICK · walk to a neighboring cell, then push the crate."
};
}
const destination = {
x: crateCell.x + direction.dx,
z: crateCell.z + direction.dz
};
if (crateDestinationIsFree(destination.x, destination.z)) {
return {
type: "push",
direction,
destination,
color: 0x49b979,
text: "PUSH · the cell beyond the crate is free."
};
}
return {
type: "push-blocked",
direction,
destination,
color: 0xe76b62,
text: "PUSH BLOCKED · the cell beyond the crate is occupied."
};
}
if (sameCell(cell, playerCell)) {
return {
type: "current",
color: 0xffffff,
text: "The player currently occupies this cell."
};
}
const direction = adjacentDirection(playerCell, cell);
if (direction) {
return {
type: "walk",
direction,
color: 0x49b979,
text: "WALK · this free cell is one step away."
};
}
return {
type: "walk-path",
color: 0x548be8,
text: "CLICK · walk around obstacles to this free cell."
};
}
function updateHover(event) {
const object = pick(event);
if (!object) {
hoverRing.visible = false;
pushArrow.visible = false;
actionHint.textContent = "Click a neighboring tile to walk, or click the crate to push.";
return;
}
const cell = object.userData.cell;
const pickType = object.userData.pickType;
const result = evaluateTarget(cell, pickType);
hoverRing.visible = true;
hoverRing.material.color.setHex(result.color);
let y = 0.075;
if (pickType === "crate") y = 0.83;
if (pickType === "wall") {
y = (wallHeights.get(key(cell.x, cell.z)) || 0.6) + 0.025;
}
hoverRing.position.set(worldX(cell.x), y, worldZ(cell.z));
actionHint.textContent = result.text;
if (result.type === "push" || result.type === "push-blocked") {
pushArrow.visible = true;
pushArrow.position.set(
worldX(crateCell.x),
1.18,
worldZ(crateCell.z)
);
pushArrow.setDirection(
new THREE.Vector3(result.direction.dx, 0, result.direction.dz).normalize()
);
pushArrow.setColor(result.color);
} else {
pushArrow.visible = false;
}
}
function handleClick(event) {
const object = pick(event);
if (!object) return;
clearAutomaticMovement();
const cell = object.userData.cell;
const pickType = object.userData.pickType;
if (pickType === "wall") {
setStatus("That cell is blocked by a wall.", "bad");
return;
}
if (pickType === "crate") {
const direction = adjacentDirection(playerCell, crateCell);
if (direction) {
attemptMove(direction.dx, direction.dz);
} else {
planApproachToCrate();
}
return;
}
if (sameCell(cell, playerCell)) {
setStatus("The player is already in this cell.", "neutral");
return;
}
const path = findPath(playerCell, cell);
if (!path) {
setStatus("No walking route exists without pushing the crate.", "bad");
return;
}
autoPath = path;
autoPush = null;
setStatus("Walking to the selected cell…", "neutral");
}
// ------------------------------------------------------------
// Direct camera controls: orbit, zoom, and picking
// ------------------------------------------------------------
let drag = null;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
clearAutomaticMovement();
drag = {
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (drag) {
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
if (
Math.hypot(
event.clientX - drag.startX,
event.clientY - drag.startY
) > 5
) {
drag.moved = true;
}
if (drag.moved) {
cameraYaw -= dx * 0.007;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + dy * 0.005,
0.52,
1.16
);
updateCamera();
hoverRing.visible = false;
pushArrow.visible = false;
}
} else {
updateHover(event);
}
});
renderer.domElement.addEventListener("pointerup", event => {
if (!drag) return;
const wasClick = !drag.moved;
drag = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (wasClick) {
handleClick(event);
updateHover(event);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
drag = null;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!drag) {
hoverRing.visible = false;
pushArrow.visible = false;
}
});
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * (event.deltaY > 0 ? 0.9 : 1.1),
0.65,
1.8
);
camera.updateProjectionMatrix();
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
// ------------------------------------------------------------
// Keyboard and UI controls
// ------------------------------------------------------------
window.addEventListener("keydown", event => {
const keyName = event.key.toLowerCase();
if (["arrowup", "arrowdown", "arrowleft", "arrowright", "w", "a", "s", "d"].includes(keyName)) {
event.preventDefault();
clearAutomaticMovement();
if (keyName === "w" || keyName === "arrowup") attemptMove(0, -1);
if (keyName === "s" || keyName === "arrowdown") attemptMove(0, 1);
if (keyName === "a" || keyName === "arrowleft") attemptMove(-1, 0);
if (keyName === "d" || keyName === "arrowright") attemptMove(1, 0);
}
if (keyName === "r") resetGame();
if (keyName === "o") toggleOccupancy();
});
document.querySelectorAll(".dpad button").forEach(button => {
button.addEventListener("click", () => {
clearAutomaticMovement();
attemptMove(
Number(button.dataset.dx),
Number(button.dataset.dz)
);
});
});
function toggleOccupancy() {
occupancyVisible = !occupancyVisible;
occupancyGroup.visible = occupancyVisible;
occupancyButton.setAttribute("aria-pressed", String(occupancyVisible));
occupancyButton.textContent = `Occupied cells: ${occupancyVisible ? "ON" : "OFF"}`;
}
occupancyButton.addEventListener("click", toggleOccupancy);
function resetGame() {
playerCell.x = START_PLAYER.x;
playerCell.z = START_PLAYER.z;
crateCell.x = START_CRATE.x;
crateCell.z = START_CRATE.z;
playerGroup.position.set(worldX(playerCell.x), 0.04, worldZ(playerCell.z));
crateGroup.position.set(worldX(crateCell.x), 0.04, worldZ(crateCell.z));
playerGroup.rotation.y = 0;
crateBody.userData.cell = { ...crateCell };
animation = null;
clearAutomaticMovement();
solved = false;
crateFlash = 0;
goalTile.material.opacity = 0.3;
goalRing.material.opacity = 0.92;
setStatus("Push the crate around the bend and onto the green goal.", "neutral");
actionHint.textContent = "Click a neighboring tile to walk, or click the crate to push.";
}
resetButton.addEventListener("click", resetGame);
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
function updateMarkers() {
crateOccupancy.position.set(
crateGroup.position.x,
0.055,
crateGroup.position.z
);
playerOccupancy.position.set(
playerGroup.position.x,
0.055,
playerGroup.position.z
);
}
renderer.setAnimationLoop(() => {
const dt = clock.getDelta();
if (animation) {
animation.elapsed += dt;
const t = Math.min(animation.elapsed / animation.duration, 1);
const eased = t * t * (3 - 2 * t);
playerGroup.position.lerpVectors(
animation.playerFrom,
animation.playerTo,
eased
);
if (animation.crateFrom && animation.crateTo) {
crateGroup.position.lerpVectors(
animation.crateFrom,
animation.crateTo,
eased
);
}
if (t >= 1) {
animation = null;
if (!solved && sameCell(crateCell, GOAL)) {
solved = true;
goalTile.material.opacity = 0.55;
goalRing.material.opacity = 1;
setStatus(
"Solved! The crate is parked on the green goal tile.",
"good"
);
}
}
} else {
stepAutomaticMovement();
}
if (crateFlash > 0) {
crateFlash = Math.max(0, crateFlash - dt * 3.2);
crateMaterial.emissive.setHex(0xff3f32);
crateMaterial.emissiveIntensity = crateFlash * 1.5;
} else {
crateMaterial.emissive.setHex(0x000000);
crateMaterial.emissiveIntensity = 0;
}
const pulse = 1 + Math.sin(clock.elapsedTime * 3.2) * 0.07;
goalRing.scale.setScalar(pulse);
updateMarkers();
renderer.render(scene, camera);
});
updateMarkers();
document.querySelector("#loading").remove();
</script>
</body>
</html>
```