Prompt specification
Build or customize the Three.js 3D scene "Gravity Arrow and Supported Cube" 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: Gravity Arrow and Supported Cube
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/gravity-arrow-and-supported-cube-x3453
Scene Description Prompt:
Model a cube inside a transparent box with one adjustable gravity arrow. Label the direction change as a game rule and show the current support surface. Build this with Three.js from cdnjs as a stylized scene in one self-contained HTML file.
Working Three.js Starter (gravity-arrow-and-supported-cube-x3453):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Gravity Rule — Three.js</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 24, 42, 0.76);
--panel-border: rgba(149, 221, 255, 0.18);
--text: #edf8ff;
--muted: #8da9bd;
--cyan: #62e7ff;
--mint: #61f2c2;
--amber: #ffbd59;
--amber-soft: rgba(255, 189, 89, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #10243b 0%, #07111f 48%, #040a12 100%);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
top: 24px;
left: 28px;
z-index: 4;
pointer-events: none;
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
width: 13px;
height: 13px;
border: 2px solid var(--amber);
transform: rotate(45deg);
box-shadow: 0 0 18px rgba(255, 189, 89, 0.45);
}
.brand-name {
font-size: 12px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brand-sub {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--panel-border);
border-radius: 18px;
background:
linear-gradient(145deg, rgba(21, 43, 66, 0.76), rgba(7, 18, 32, 0.84));
box-shadow:
0 20px 55px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.rule-panel {
top: 92px;
left: 24px;
width: 330px;
padding: 19px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: var(--amber);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 22px;
height: 2px;
background: var(--amber);
box-shadow: 0 0 12px rgba(255, 189, 89, 0.7);
}
.rule-title {
margin: 13px 0 7px;
font-size: 20px;
line-height: 1.22;
letter-spacing: -0.025em;
}
.rule-copy {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.rule-event {
min-height: 38px;
margin-top: 13px;
padding: 10px 11px;
border: 1px solid rgba(255, 189, 89, 0.17);
border-radius: 10px;
background: var(--amber-soft);
color: #ffd99f;
font-size: 10px;
font-weight: 700;
line-height: 1.45;
letter-spacing: 0.07em;
text-transform: uppercase;
transition: 180ms ease;
}
.rule-event.changed {
border-color: rgba(255, 189, 89, 0.55);
background: rgba(255, 189, 89, 0.23);
box-shadow: 0 0 24px rgba(255, 189, 89, 0.12);
}
.control-section {
margin-top: 19px;
padding-top: 16px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.section-title {
color: #c9e2f1;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.live-dot {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--mint);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.live-dot::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 10px var(--mint);
}
.slider-row + .slider-row {
margin-top: 13px;
}
.slider-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.slider-value {
color: var(--amber);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
appearance: none;
-webkit-appearance: none;
background: linear-gradient(
90deg,
rgba(255, 189, 89, 0.8),
rgba(98, 231, 255, 0.2)
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #102238;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--amber);
box-shadow: 0 0 0 1px var(--amber), 0 0 14px rgba(255, 189, 89, 0.45);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #102238;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 0 1px var(--amber), 0 0 14px rgba(255, 189, 89, 0.45);
}
.vector-readout {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 15px;
}
.vector-cell {
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 9px;
background: rgba(0, 0, 0, 0.15);
text-align: center;
}
.vector-axis {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.13em;
}
.vector-number {
display: block;
margin-top: 3px;
color: var(--cyan);
font-size: 12px;
font-weight: 750;
font-variant-numeric: tabular-nums;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 15px;
}
button {
flex: 1;
min-height: 36px;
border: 1px solid rgba(98, 231, 255, 0.2);
border-radius: 10px;
background: rgba(98, 231, 255, 0.07);
color: #cdefff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
cursor: pointer;
transition: 150ms ease;
}
button:hover {
border-color: rgba(98, 231, 255, 0.55);
background: rgba(98, 231, 255, 0.13);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
.support-panel {
top: 24px;
right: 24px;
width: 252px;
padding: 17px;
}
.support-value {
margin-top: 12px;
color: var(--mint);
font-size: 27px;
font-weight: 850;
line-height: 1;
letter-spacing: -0.04em;
text-shadow: 0 0 24px rgba(97, 242, 194, 0.24);
}
.support-detail {
min-height: 32px;
margin-top: 8px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.target-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.target-row strong {
color: var(--amber);
font-size: 10px;
}
.scene-label {
position: fixed;
z-index: 3;
pointer-events: none;
white-space: nowrap;
transform: translate(-50%, -50%);
}
#surface-label {
padding: 7px 10px;
border: 1px solid rgba(97, 242, 194, 0.4);
border-radius: 8px;
background: rgba(5, 25, 29, 0.78);
color: var(--mint);
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
backdrop-filter: blur(8px);
}
#arrow-label {
padding: 5px 8px;
border: 1px solid rgba(255, 189, 89, 0.34);
border-radius: 99px;
background: rgba(34, 24, 12, 0.76);
color: #ffd497;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
backdrop-filter: blur(8px);
}
.hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 22px;
transform: translateX(-50%);
padding: 9px 14px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 99px;
background: rgba(4, 13, 23, 0.66);
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
pointer-events: none;
backdrop-filter: blur(12px);
white-space: nowrap;
}
.hint b {
color: var(--amber);
font-weight: 850;
}
@media (max-width: 760px) {
.brand {
top: 16px;
left: 16px;
}
.rule-panel {
top: 72px;
left: 12px;
width: min(300px, calc(100vw - 24px));
padding: 14px;
}
.support-panel {
top: auto;
right: 12px;
bottom: 54px;
width: 220px;
padding: 13px;
}
.support-value {
font-size: 22px;
}
.hint {
max-width: calc(100vw - 20px);
overflow: hidden;
text-overflow: ellipsis;
}
.rule-copy {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="brand">
<div class="brand-mark"></div>
<div>
<div class="brand-name">Gravity Rule</div>
<div class="brand-sub">Support Surface Simulator</div>
</div>
</div>
<section class="panel rule-panel">
<div class="eyebrow">Game Rule 01</div>
<h1 class="rule-title">Change gravity.<br />Change the floor.</h1>
<p class="rule-copy">
Redirect the gravity vector. The cube accelerates toward the new
direction, and the contacted wall becomes its support surface.
</p>
<div id="rule-event" class="rule-event" aria-live="polite">
Direction change is a game rule
</div>
<div class="control-section">
<div class="section-head">
<span class="section-title">Gravity Controls</span>
<span class="live-dot">Active</span>
</div>
<div class="slider-row">
<label class="slider-label" for="azimuth">
<span>Direction</span>
<span id="azimuth-value" class="slider-value">0°</span>
</label>
<input
id="azimuth"
type="range"
min="-180"
max="180"
step="1"
value="0"
aria-label="Gravity direction"
/>
</div>
<div class="slider-row">
<label class="slider-label" for="elevation">
<span>Lift</span>
<span id="elevation-value" class="slider-value">0°</span>
</label>
<input
id="elevation"
type="range"
min="0"
max="180"
step="1"
value="0"
aria-label="Gravity elevation"
/>
</div>
<div class="vector-readout">
<div class="vector-cell">
<span class="vector-axis">X</span>
<span id="vector-x" class="vector-number">0.00</span>
</div>
<div class="vector-cell">
<span class="vector-axis">Y</span>
<span id="vector-y" class="vector-number">-1.00</span>
</div>
<div class="vector-cell">
<span class="vector-axis">Z</span>
<span id="vector-z" class="vector-number">0.00</span>
</div>
</div>
<div class="button-row">
<button id="pause-button" type="button">Pause</button>
<button id="reset-button" type="button">Reset</button>
</div>
</div>
</section>
<section class="panel support-panel">
<div class="eyebrow">Current Support</div>
<div id="support-value" class="support-value" aria-live="polite">AIRBORNE</div>
<div id="support-detail" class="support-detail">
No wall contact yet.
</div>
<div class="target-row">
<span>Next target</span>
<strong id="target-value">FLOOR</strong>
</div>
</section>
<div id="surface-label" class="scene-label">SUPPORT • AIRBORNE</div>
<div id="arrow-label" class="scene-label">Drag gravity</div>
<div class="hint">
<b>Drag arrow</b> to redirect gravity •
<b>Drag background</b> to orbit •
<b>Scroll</b> to zoom
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 15, 30);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, -0.1, 0);
let cameraTheta = 0.72;
let cameraPhi = 1.03;
let cameraRadius = 12.8;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphereLight = new THREE.HemisphereLight(
0xaeeaff,
0x07101c,
1.65
);
scene.add(hemisphereLight);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x43dfff, 16, 18, 2);
rimLight.position.set(-6, 2, 4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa84f, 12, 12, 2);
warmLight.position.set(3, 1, 3);
scene.add(warmLight);
// -------------------------------------------------------------------------
// Dimensions and simulation state
// -------------------------------------------------------------------------
const BOX = {
x: 4,
y: 3,
z: 2.5
};
const CUBE_HALF = 0.58;
const GRAVITY_STRENGTH = 10.5;
const cubePosition = new THREE.Vector3(0, 0.55, 0);
const cubeVelocity = new THREE.Vector3();
const gravityDirection = new THREE.Vector3(0, -1, 0);
let azimuth = 0;
let elevation = 0;
let paused = false;
let currentContacts = new Set();
// -------------------------------------------------------------------------
// Exterior pedestal
// -------------------------------------------------------------------------
const pedestal = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
new THREE.MeshStandardMaterial({
color: 0x07111b,
roughness: 0.92,
metalness: 0.05
})
);
pedestal.rotation.x = -Math.PI / 2;
pedestal.position.y = -3.35;
pedestal.receiveShadow = true;
scene.add(pedestal);
const exteriorGrid = new THREE.GridHelper(
30,
30,
0x17415a,
0x10283a
);
exteriorGrid.position.y = -3.33;
exteriorGrid.material.transparent = true;
exteriorGrid.material.opacity = 0.28;
scene.add(exteriorGrid);
// -------------------------------------------------------------------------
// Transparent box
// -------------------------------------------------------------------------
const boxGeometry = new THREE.BoxGeometry(
BOX.x * 2,
BOX.y * 2,
BOX.z * 2
);
const glass = new THREE.Mesh(
boxGeometry,
new THREE.MeshPhysicalMaterial({
color: 0x83dcff,
transparent: true,
opacity: 0.055,
roughness: 0.18,
metalness: 0.05,
side: THREE.DoubleSide,
depthWrite: false
})
);
scene.add(glass);
const boxEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(boxGeometry),
new THREE.LineBasicMaterial({
color: 0x8adcff,
transparent: true,
opacity: 0.72
})
);
scene.add(boxEdges);
// Subtle interior floor grid.
const gridVertices = [];
for (let x = -BOX.x; x <= BOX.x + 0.001; x += 0.5) {
gridVertices.push(
x, -BOX.y + 0.012, -BOX.z,
x, -BOX.y + 0.012, BOX.z
);
}
for (let z = -BOX.z; z <= BOX.z + 0.001; z += 0.5) {
gridVertices.push(
-BOX.x, -BOX.y + 0.012, z,
BOX.x, -BOX.y + 0.012, z
);
}
const interiorGridGeometry = new THREE.BufferGeometry();
interiorGridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const interiorGrid = new THREE.LineSegments(
interiorGridGeometry,
new THREE.LineBasicMaterial({
color: 0x3b7896,
transparent: true,
opacity: 0.28
})
);
scene.add(interiorGrid);
// -------------------------------------------------------------------------
// Cube
// -------------------------------------------------------------------------
const cubeGroup = new THREE.Group();
const cubeMaterial = new THREE.MeshStandardMaterial({
color: 0xffad54,
roughness: 0.3,
metalness: 0.14,
emissive: 0x4a1700,
emissiveIntensity: 0.12
});
const cubeMesh = new THREE.Mesh(
new THREE.BoxGeometry(CUBE_HALF * 2, CUBE_HALF * 2, CUBE_HALF * 2),
cubeMaterial
);
cubeMesh.castShadow = true;
cubeMesh.receiveShadow = true;
cubeGroup.add(cubeMesh);
const cubeEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(cubeMesh.geometry),
new THREE.LineBasicMaterial({
color: 0xffedca,
transparent: true,
opacity: 0.9
})
);
cubeGroup.add(cubeEdges);
// A small face inset makes the cube read more like a game object.
const faceInset = new THREE.Mesh(
new THREE.PlaneGeometry(0.48, 0.48),
new THREE.MeshBasicMaterial({
color: 0xffe4aa,
transparent: true,
opacity: 0.55,
side: THREE.DoubleSide
})
);
faceInset.position.z = CUBE_HALF + 0.002;
cubeGroup.add(faceInset);
const faceInsetOutline = new THREE.LineSegments(
new THREE.EdgesGeometry(faceInset.geometry),
new THREE.LineBasicMaterial({
color: 0x7a3c0b,
transparent: true,
opacity: 0.65
})
);
faceInsetOutline.position.copy(faceInset.position);
cubeGroup.add(faceInsetOutline);
scene.add(cubeGroup);
// -------------------------------------------------------------------------
// Support surface highlights
// -------------------------------------------------------------------------
const surfaceObjects = {};
function createSurface(key, width, height, position, rotation) {
const group = new THREE.Group();
const geometry = new THREE.PlaneGeometry(width, height);
const material = new THREE.MeshBasicMaterial({
color: 0x61f2c2,
transparent: true,
opacity: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const fill = new THREE.Mesh(geometry, material);
group.add(fill);
const borderMaterial = new THREE.LineBasicMaterial({
color: 0x8affdc,
transparent: true,
opacity: 0
});
const border = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
borderMaterial
);
group.add(border);
group.position.copy(position);
group.rotation.set(rotation.x, rotation.y, rotation.z);
scene.add(group);
surfaceObjects[key] = { group, material, borderMaterial };
}
createSurface(
"floor",
BOX.x * 2,
BOX.z * 2,
new THREE.Vector3(0, -BOX.y + 0.018, 0),
new THREE.Euler(-Math.PI / 2, 0, 0)
);
createSurface(
"ceiling",
BOX.x * 2,
BOX.z * 2,
new THREE.Vector3(0, BOX.y - 0.018, 0),
new THREE.Euler(Math.PI / 2, 0, 0)
);
createSurface(
"left",
BOX.z * 2,
BOX.y * 2,
new THREE.Vector3(-BOX.x + 0.018, 0, 0),
new THREE.Euler(0, Math.PI / 2, 0)
);
createSurface(
"right",
BOX.z * 2,
BOX.y * 2,
new THREE.Vector3(BOX.x - 0.018, 0, 0),
new THREE.Euler(0, -Math.PI / 2, 0)
);
createSurface(
"front",
BOX.x * 2,
BOX.y * 2,
new THREE.Vector3(0, 0, BOX.z - 0.018),
new THREE.Euler(0, 0, 0)
);
createSurface(
"back",
BOX.x * 2,
BOX.y * 2,
new THREE.Vector3(0, 0, -BOX.z + 0.018),
new THREE.Euler(0, Math.PI, 0)
);
const surfaceNames = {
floor: "FLOOR",
ceiling: "CEILING",
left: "LEFT WALL",
right: "RIGHT WALL",
front: "FRONT WALL",
back: "BACK WALL"
};
// -------------------------------------------------------------------------
// The single adjustable gravity arrow
// -------------------------------------------------------------------------
const arrowTail = new THREE.Vector3(-2.75, 1.8, 0.75);
const arrowGroup = new THREE.Group();
arrowGroup.position.copy(arrowTail);
scene.add(arrowGroup);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: 0xffb84f,
emissive: 0xff7a13,
emissiveIntensity: 0.72,
roughness: 0.28,
metalness: 0.2,
depthTest: false,
transparent: true,
opacity: 0.98
});
const arrowShaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 1.05, 18),
arrowMaterial
);
arrowShaft.position.y = 0.525;
arrowGroup.add(arrowShaft);
const arrowHead = new THREE.Mesh(
new THREE.ConeGeometry(0.24, 0.5, 24),
arrowMaterial
);
arrowHead.position.y = 1.3;
arrowGroup.add(arrowHead);
const arrowTailMesh = new THREE.Mesh(
new THREE.SphereGeometry(0.12, 18, 12),
arrowMaterial
);
arrowGroup.add(arrowTailMesh);
const arrowMeshes = [arrowShaft, arrowHead, arrowTailMesh];
for (const mesh of arrowMeshes) {
mesh.userData.isGravityArrow = true;
mesh.renderOrder = 20;
}
const upVector = new THREE.Vector3(0, 1, 0);
const arrowQuaternion = new THREE.Quaternion();
// -------------------------------------------------------------------------
// UI references
// -------------------------------------------------------------------------
const azimuthInput = document.getElementById("azimuth");
const elevationInput = document.getElementById("elevation");
const azimuthValue = document.getElementById("azimuth-value");
const elevationValue = document.getElementById("elevation-value");
const vectorX = document.getElementById("vector-x");
const vectorY = document.getElementById("vector-y");
const vectorZ = document.getElementById("vector-z");
const ruleEvent = document.getElementById("rule-event");
const supportValue = document.getElementById("support-value");
const supportDetail = document.getElementById("support-detail");
const targetValue = document.getElementById("target-value");
const surfaceLabel = document.getElementById("surface-label");
const arrowLabel = document.getElementById("arrow-label");
const pauseButton = document.getElementById("pause-button");
const resetButton = document.getElementById("reset-button");
// -------------------------------------------------------------------------
// Gravity helpers
// -------------------------------------------------------------------------
function directionFromAngles() {
const az = THREE.MathUtils.degToRad(azimuth);
const el = THREE.MathUtils.degToRad(elevation);
return new THREE.Vector3(
Math.sin(az) * Math.sin(el),
-Math.cos(el),
Math.cos(az) * Math.sin(el)
).normalize();
}
function getTargetSurface(direction) {
const ax = Math.abs(direction.x);
const ay = Math.abs(direction.y);
const az = Math.abs(direction.z);
if (ay >= ax && ay >= az) {
return direction.y < 0 ? "floor" : "ceiling";
}
if (ax >= az) {
return direction.x < 0 ? "left" : "right";
}
return direction.z < 0 ? "back" : "front";
}
let targetSurface = "floor";
function setGravityDirection(direction, announce = true) {
const changed = direction.dot(gravityDirection) < 0.9995;
gravityDirection.copy(direction).normalize();
arrowQuaternion.setFromUnitVectors(upVector, gravityDirection);
arrowGroup.quaternion.copy(arrowQuaternion);
targetSurface = getTargetSurface(gravityDirection);
if (changed && announce) {
ruleEvent.textContent =
`Direction changed → target: ${surfaceNames[targetSurface]}`;
ruleEvent.classList.add("changed");
window.clearTimeout(ruleEvent.changeTimer);
ruleEvent.changeTimer = window.setTimeout(() => {
ruleEvent.classList.remove("changed");
}, 850);
}
updateGravityReadout();
}
function setGravityAngles(nextAzimuth, nextElevation, announce = true) {
azimuth = THREE.MathUtils.clamp(nextAzimuth, -180, 180);
elevation = THREE.MathUtils.clamp(nextElevation, 0, 180);
azimuthInput.value = Math.round(azimuth);
elevationInput.value = Math.round(elevation);
azimuthValue.textContent = `${Math.round(azimuth)}°`;
elevationValue.textContent = `${Math.round(elevation)}°`;
setGravityDirection(directionFromAngles(), announce);
}
function updateGravityReadout() {
vectorX.textContent = gravityDirection.x.toFixed(2);
vectorY.textContent = gravityDirection.y.toFixed(2);
vectorZ.textContent = gravityDirection.z.toFixed(2);
}
azimuthInput.addEventListener("input", () => {
setGravityAngles(Number(azimuthInput.value), Number(elevationInput.value));
});
elevationInput.addEventListener("input", () => {
setGravityAngles(Number(azimuthInput.value), Number(elevationInput.value));
});
// -------------------------------------------------------------------------
// Lightweight cube physics
// -------------------------------------------------------------------------
function dampAxis(axis, amount, dt) {
cubeVelocity[axis] *= Math.exp(-amount * dt);
}
function updatePhysics(dt) {
cubeVelocity.addScaledVector(
gravityDirection,
GRAVITY_STRENGTH * dt
);
cubePosition.addScaledVector(cubeVelocity, dt);
const restitution = 0.14;
const softImpact = 0.75;
// X-axis collisions.
if (cubePosition.x + CUBE_HALF > BOX.x) {
cubePosition.x = BOX.x - CUBE_HALF;
if (cubeVelocity.x > 0) {
cubeVelocity.x =
Math.abs(cubeVelocity.x) < softImpact
? 0
: -cubeVelocity.x * restitution;
}
} else if (cubePosition.x - CUBE_HALF < -BOX.x) {
cubePosition.x = -BOX.x + CUBE_HALF;
if (cubeVelocity.x < 0) {
cubeVelocity.x =
Math.abs(cubeVelocity.x) < softImpact
? 0
: -cubeVelocity.x * restitution;
}
}
// Y-axis collisions.
if (cubePosition.y + CUBE_HALF > BOX.y) {
cubePosition.y = BOX.y - CUBE_HALF;
if (cubeVelocity.y > 0) {
cubeVelocity.y =
Math.abs(cubeVelocity.y) < softImpact
? 0
: -cubeVelocity.y * restitution;
}
} else if (cubePosition.y - CUBE_HALF < -BOX.y) {
cubePosition.y = -BOX.y + CUBE_HALF;
if (cubeVelocity.y < 0) {
cubeVelocity.y =
Math.abs(cubeVelocity.y) < softImpact
? 0
: -cubeVelocity.y * restitution;
}
}
// Z-axis collisions.
if (cubePosition.z + CUBE_HALF > BOX.z) {
cubePosition.z = BOX.z - CUBE_HALF;
if (cubeVelocity.z > 0) {
cubeVelocity.z =
Math.abs(cubeVelocity.z) < softImpact
? 0
: -cubeVelocity.z * restitution;
}
} else if (cubePosition.z - CUBE_HALF < -BOX.z) {
cubePosition.z = -BOX.z + CUBE_HALF;
if (cubeVelocity.z < 0) {
cubeVelocity.z =
Math.abs(cubeVelocity.z) < softImpact
? 0
: -cubeVelocity.z * restitution;
}
}
const contacts = new Set();
const epsilon = 0.045;
if (Math.abs(cubePosition.x + CUBE_HALF - BOX.x) < epsilon) {
contacts.add("right");
}
if (Math.abs(cubePosition.x - CUBE_HALF + BOX.x) < epsilon) {
contacts.add("left");
}
if (Math.abs(cubePosition.y + CUBE_HALF - BOX.y) < epsilon) {
contacts.add("ceiling");
}
if (Math.abs(cubePosition.y - CUBE_HALF + BOX.y) < epsilon) {
contacts.add("floor");
}
if (Math.abs(cubePosition.z + CUBE_HALF - BOX.z) < epsilon) {
contacts.add("front");
}
if (Math.abs(cubePosition.z - CUBE_HALF + BOX.z) < epsilon) {
contacts.add("back");
}
// Friction only affects axes tangent to the contacted support.
if (contacts.has("floor") || contacts.has("ceiling")) {
dampAxis("x", 3.3, dt);
dampAxis("z", 3.3, dt);
}
if (contacts.has("left") || contacts.has("right")) {
dampAxis("y", 3.3, dt);
dampAxis("z", 3.3, dt);
}
if (contacts.has("front") || contacts.has("back")) {
dampAxis("x", 3.3, dt);
dampAxis("y", 3.3, dt);
}
currentContacts = contacts;
}
// -------------------------------------------------------------------------
// UI and scene synchronization
// -------------------------------------------------------------------------
function supportAnchor() {
if (currentContacts.has("floor")) {
return new THREE.Vector3(
cubePosition.x,
-BOX.y - 0.05,
cubePosition.z
);
}
if (currentContacts.has("ceiling")) {
return new THREE.Vector3(
cubePosition.x,
BOX.y + 0.05,
cubePosition.z
);
}
if (currentContacts.has("left")) {
return new THREE.Vector3(
-BOX.x - 0.05,
cubePosition.y,
cubePosition.z
);
}
if (currentContacts.has("right")) {
return new THREE.Vector3(
BOX.x + 0.05,
cubePosition.y,
cubePosition.z
);
}
if (currentContacts.has("front")) {
return new THREE.Vector3(
cubePosition.x,
cubePosition.y,
BOX.z + 0.05
);
}
if (currentContacts.has("back")) {
return new THREE.Vector3(
cubePosition.x,
cubePosition.y,
-BOX.z - 0.05
);
}
return cubePosition.clone();
}
function projectLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateSupportDisplay() {
const contactNames = [...currentContacts].map(
(key) => surfaceNames[key]
);
if (contactNames.length === 0) {
supportValue.textContent = "AIRBORNE";
supportValue.style.color = "#8da9bd";
supportDetail.textContent = "No wall contact yet.";
surfaceLabel.textContent = "SUPPORT • AIRBORNE";
} else {
supportValue.textContent = contactNames.join(" + ");
supportValue.style.color = "#61f2c2";
supportDetail.textContent =
contactNames.length === 1
? `The cube is resting on the ${contactNames[0].toLowerCase()}.`
: `The cube is contacting ${contactNames.length} surfaces.`;
surfaceLabel.textContent = `SUPPORT • ${contactNames.join(" + ")}`;
}
targetValue.textContent = surfaceNames[targetSurface];
for (const [key, object] of Object.entries(surfaceObjects)) {
const isCurrent = currentContacts.has(key);
const isTarget = key === targetSurface;
object.material.opacity = isCurrent
? 0.17
: isTarget
? 0.045
: 0;
object.borderMaterial.opacity = isCurrent
? 0.76
: isTarget
? 0.3
: 0;
}
}
// -------------------------------------------------------------------------
// Custom pointer controls: arrow dragging and camera orbit
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerMode = null;
let lastPointerX = 0;
let lastPointerY = 0;
function updatePointer(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;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const arrowHit = raycaster.intersectObjects(arrowMeshes, false);
pointerMode = arrowHit.length > 0 ? "gravity" : "orbit";
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor =
pointerMode === "gravity" ? "grabbing" : "move";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerMode) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const overArrow =
raycaster.intersectObjects(arrowMeshes, false).length > 0;
renderer.domElement.style.cursor = overArrow ? "grab" : "default";
return;
}
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (pointerMode === "gravity") {
const nextAzimuth = azimuth + deltaX * 0.012;
const nextElevation = elevation - deltaY * 0.012;
setGravityAngles(nextAzimuth, nextElevation);
} else if (pointerMode === "orbit") {
cameraTheta -= deltaX * 0.005;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.32,
1.48
);
updateCamera();
}
});
function endPointerInteraction(event) {
pointerMode = null;
renderer.domElement.style.cursor = "default";
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener(
"pointerup",
endPointerInteraction
);
renderer.domElement.addEventListener(
"pointercancel",
endPointerInteraction
);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.008,
8,
20
);
updateCamera();
},
{ passive: false }
);
// Keyboard direction control.
window.addEventListener("keydown", (event) => {
const step = 7;
if (event.key === "ArrowLeft") {
event.preventDefault();
setGravityAngles(azimuth - step, elevation);
} else if (event.key === "ArrowRight") {
event.preventDefault();
setGravityAngles(azimuth + step, elevation);
} else if (event.key === "ArrowUp") {
event.preventDefault();
setGravityAngles(azimuth, elevation + step);
} else if (event.key === "ArrowDown") {
event.preventDefault();
setGravityAngles(azimuth, elevation - step);
}
});
// -------------------------------------------------------------------------
// Pause and reset
// -------------------------------------------------------------------------
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
resetButton.addEventListener("click", () => {
cubePosition.set(0, 0.55, 0);
cubeVelocity.set(0, 0, 0);
cubeGroup.rotation.set(0, 0, 0);
setGravityAngles(0, 0, false);
currentContacts = new Set();
cameraTheta = 0.72;
cameraPhi = 1.03;
cameraRadius = 12.8;
updateCamera();
ruleEvent.textContent = "Direction change is a game rule";
ruleEvent.classList.remove("changed");
});
// -------------------------------------------------------------------------
// Resize and animation loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
const clock = new THREE.Clock();
const arrowLabelPosition = new THREE.Vector3();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.033);
if (!paused) {
updatePhysics(dt);
}
cubeGroup.position.copy(cubePosition);
const speed = cubeVelocity.length();
cubeGroup.rotation.y += dt * (0.18 + speed * 0.12);
updateSupportDisplay();
projectLabel(surfaceLabel, supportAnchor());
arrowLabelPosition
.copy(arrowTail)
.addScaledVector(gravityDirection, 1.75)
.add(new THREE.Vector3(0, 0.12, 0));
projectLabel(arrowLabel, arrowLabelPosition);
renderer.render(scene, camera);
}
setGravityAngles(0, 0, false);
animate();
</script>
</body>
</html>
```