JSFiddle - React, Tailwind, and code Playground
by Katarn
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>3D Cube Game</title>
</head>
<body>
<div id="menu">
<div>
<h1>3D Cube Game</h1>
<button onclick="startGame()">Play</button>
</div>
</div>
<div id="gameOverMenu">
<div>
<h1>Game Over</h1>
<button onclick="restartGame()">Restart</button>
<button onclick="goToMenu()">Exit</button>
</div>
</div>
<div id="score" style="display: none;">Score: 0</div>
</body>
</html>
CSS
body { margin: 0; overflow: hidden; }
#menu, #gameOverMenu {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background: rgba(0, 0, 0, 0.8);
color: white;
font-family: Arial, sans-serif;
font-size: 24px;
display: none;
}
button {
margin: 10px;
padding: 10px 20px;
font-size: 18px;
}
#score {
position: absolute;
top: 10px;
left: 10px;
font-size: 24px;
color: white;
font-family: Arial, sans-serif;
}
JavaScript
let scene, camera, renderer, cube, floor, sky, obstacles = [], frame = 0, playing = false, score = 0, scoreInterval;
const clock = new THREE.Clock();
const gravity = 0.5;
let velocityY = 0;
let isJumping = false;
init();
showMenu();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
// Create the floor
const floorGeometry = new THREE.PlaneGeometry(200, 200);
const floorMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.rotation.x = 9;
floor.position.y = 0;
floor.receiveShadow = true;
scene.add(floor);
console.log('Floor created:', floor);
// Create the player cube
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x0000ff });
cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 0.5, 0);
cube.castShadow = true;
scene.add(cube);
// Create the sky
const skyGeometry = new THREE.SphereGeometry(100, 32, 32);
const skyMaterial = new THREE.MeshBasicMaterial({ color: 0x87CEEB, side: THREE.BackSide });
sky = new THREE.Mesh(skyGeometry, skyMaterial);
scene.add(sky);
console.log('Sky created:', sky);
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
scene.add(ambientLight);
const directionalLight =...