Certainly! Below is a step-by-step implementation of your project requirements for creating a 3D voxel-based world using Three.js and Cannon.js. The code includes comments and explanations to help you understand each part of the implementation.
1. Setup Three.js Scene
// Import THREE.js and Cannon.js libraries
import * as THREE from 'three';
import * as CANNON from 'cannon-es';
// Create the scene
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87ceeb); // Sky blue color
// Create the camera
const camera = new THREE.PerspectiveCamera(
75, // Field of view
window.innerWidth / window.innerHeight, // Aspect ratio
0.1, // Near clipping plane
1000 // Far clipping plane
);
// Create the renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
2. Initialize Cannon.js Physics World
// Create the physics world
const physicsWorld = new CANNON.World();
physicsWorld.gravity.set(0, -9.82, 0); // Standard Earth gravity
// Define a physics material with zero friction and zero restitution
const defaultMaterial = new CANNON.Material('defaultMaterial');
const defaultContactMaterial = new CANNON.ContactMaterial(
defaultMaterial,
defaultMaterial,
{
friction: 0.0,
restitution: 0.0,
}
);
physicsWorld.addContactMaterial(defaultContactMaterial);
physicsWorld.defaultContactMaterial = defaultContactMaterial;
3. Chunk Management for Terrain
// Chunk parameters
const chunkSize = 16;
const renderDistance = 3;
const chunks = {};
// Helper function to get chunk ID
function getChunkID(x, z) {
const chunkX = Math.floor(x / chunkSize);
const chunkZ = Math.floor(z / chunkSize);
return `${chunkX}_${chunkZ}`;
}
// Function to create ground chunk
function createGroundChunk(chunkX, chunkZ) {
const simplex = new SimplexNoise(); // Assuming SimplexNoise is imported
// Create height data
const size = chunkSize + 1;
const heightData = [];
for (let i = 0; i < size; i++) {
heightData[i] = [];
for (let j = 0; j < size; j++) {
const x = (chunkX * chunkSize) + i;
const z = (chunkZ * chunkSize) + j;
const y = Math.floor(simplex.noise2D(x / 50, z / 50) * 5);
heightData[i][j] = y;
}
}
// Create geometry
const geometry = new THREE.PlaneGeometry(
chunkSize,
chunkSize,
chunkSize,
chunkSize
);
geometry.rotateX(-Math.PI / 2);
// Update vertex positions based on height data
for (let i = 0; i < geometry.attributes.position.count; i++) {
const vertex = new THREE.Vector3().fromBufferAttribute(
geometry.attributes.position,
i
);
const x = Math.floor(vertex.x + chunkSize / 2);
const z = Math.floor(vertex.z + chunkSize / 2);
vertex.y = heightData[x][z];
geometry.attributes.position.setXYZ(i, vertex.x, vertex.y, vertex.z);
}
geometry.computeVertexNormals();
// Create mesh
const material = new THREE.MeshLambertMaterial({ color: 0x228B22 });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(
chunkX * chunkSize,
0,
chunkZ * chunkSize
);
scene.add(mesh);
// Create physics shape
const shape = new CANNON.Heightfield(heightData, {
elementSize: 1,
});
const body = new CANNON.Body({ mass: 0 });
body.addShape(shape);
body.position.set(
mesh.position.x - chunkSize / 2,
0,
mesh.position.z - chunkSize / 2
);
physicsWorld.addBody(body);
// Store the chunk
chunks[getChunkID(chunkX * chunkSize, chunkZ * chunkSize)] = {
mesh,
body,
};
}
// Function to load chunks around the player
function loadChunks(playerPosition) {
const currentChunkX = Math.floor(playerPosition.x / chunkSize);
const currentChunkZ = Math.floor(playerPosition.z / chunkSize);
for (let dx = -renderDistance; dx <= renderDistance; dx++) {
for (let dz = -renderDistance; dz <= renderDistance; dz++) {
const chunkX = currentChunkX + dx;
const chunkZ = currentChunkZ + dz;
const chunkID = `${chunkX}_${chunkZ}`;
if (!chunks[chunkID]) {
createGroundChunk(chunkX, chunkZ);
}
}
}
}
4. Player Setup
// Create player physics body
const playerBody = new CANNON.Body({
mass: 1,
shape: new CANNON.Sphere(1),
material: defaultMaterial,
});
playerBody.position.set(0, 10, 0);
playerBody.fixedRotation = true; // Prevent tipping over
physicsWorld.addBody(playerBody);
// Create a dummy THREE.Mesh (invisible player representation)
const playerMesh = new THREE.Mesh(
new THREE.SphereGeometry(1),
new THREE.MeshBasicMaterial({ visible: false })
);
scene.add(playerMesh);
5. Controls and Movement
const keysPressed = {};
const movementSpeed = 5;
const jumpSpeed = 5;
// Event listeners for key presses
document.addEventListener('keydown', (event) => {
keysPressed[event.code] = true;
});
document.addEventListener('keyup', (event) => {
keysPressed[event.code] = false;
});
// Mouse movement variables
let rotation = { x: 0, y: 0 };
let rotationSpeed = { x: 0, y: 0 };
const rotationDamping = 0.1;
const rotationSpeedMax = 0.05;
// Event listeners for mouse movement
document.addEventListener('mousemove', (event) => {
rotationSpeed.y -= event.movementX * 0.002;
rotationSpeed.x -= event.movementY * 0.002;
});
6. Camera Setup
// Position the camera to follow the player smoothly
function updateCameraPosition() {
camera.position.lerp(
new THREE.Vector3(
playerBody.position.x,
playerBody.position.y + 2,
playerBody.position.z
),
0.1
);
// Apply rotation with damping
rotation.x += rotationSpeed.x;
rotation.y += rotationSpeed.y;
// Limit vertical rotation
rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, rotation.x));
// Reset rotation speed with damping
rotationSpeed.x *= (1 - rotationDamping);
rotationSpeed.y *= (1 - rotationDamping);
camera.rotation.order = 'YXZ';
camera.rotation.y = rotation.y;
camera.rotation.x = rotation.x;
}
7. Day-Night Cycle
let dayDuration = 60; // Duration in seconds
let timeOfDay = 0; // Time counter
// Create sun and moon
const sun = new THREE.DirectionalLight(0xffffff, 1);
const moon = new THREE.DirectionalLight(0x8888ff, 0.2);
sun.position.set(0, 1, 0);
moon.position.set(0, -1, 0);
scene.add(sun);
scene.add(moon);
// Create sun and moon meshes
const sunMesh = new THREE.Mesh(
new THREE.SphereGeometry(5),
new THREE.MeshBasicMaterial({ color: 0xffff00 })
);
const moonMesh = new THREE.Mesh(
new THREE.SphereGeometry(5),
new THREE.MeshBasicMaterial({ color: 0x8888ff })
);
scene.add(sunMesh);
scene.add(moonMesh);
// Create stars
const starGeometry = new THREE.BufferGeometry();
const starMaterial = new THREE.PointsMaterial({ color: 0xffffff });
const starVertices = [];
for (let i = 0; i < 1000; i++) {
starVertices.push(
THREE.MathUtils.randFloatSpread(2000),
THREE.MathUtils.randFloatSpread(2000),
THREE.MathUtils.randFloatSpread(2000)
);
}
starGeometry.setAttribute(
'position',
new THREE.Float32BufferAttribute(starVertices, 3)
);
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
// Update day-night cycle
function updateDayNightCycle(deltaTime) {
timeOfDay += deltaTime;
const cycleProgress = (timeOfDay % dayDuration) / dayDuration;
const angle = cycleProgress * Math.PI * 2;
// Update sun and moon positions
sun.position.set(
Math.cos(angle) * 100,
Math.sin(angle) * 100,
0
);
moon.position.set(
Math.cos(angle + Math.PI) * 100,
Math.sin(angle + Math.PI) * 100,
0
);
sunMesh.position.copy(sun.position);
moonMesh.position.copy(moon.position);
// Adjust light intensities
sun.intensity = Math.max(0, Math.sin(angle));
moon.intensity = Math.max(0, -Math.sin(angle));
// Change sky color
const skyColor = new THREE.Color();
skyColor.lerpColors(
new THREE.Color(0x000000), // Night color
new THREE.Color(0x87ceeb), // Day color
sun.intensity
);
scene.background = skyColor;
// Show/hide stars
stars.visible = sun.intensity < 0.1;
}
// Adjust day-night cycle duration with J key and arrow keys
document.addEventListener('keydown', (event) => {
if (event.code === 'KeyJ') {
if (keysPressed['ArrowUp']) {
dayDuration += 10;
} else if (keysPressed['ArrowDown']) {
dayDuration = Math.max(10, dayDuration - 10);
}
}
});
8. Block Placement and Removal
// Raycaster for block placement/removal
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
// Function to create a physical block
function createPhysicalBlock(x, y, z) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
scene.add(mesh);
const shape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5));
const body = new CANNON.Body({ mass: 0 });
body.addShape(shape);
body.position.set(x, y, z);
physicsWorld.addBody(body);
return { mesh, body };
}
// Mouse event handlers
function onPointerDown(event) {
// Update pointer coordinates
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Update raycaster
raycaster.setFromCamera(pointer, camera);
// Objects to intersect
const objects = Object.values(chunks).map(chunk => chunk.mesh);
// Check for intersections
const intersects = raycaster.intersectObjects(objects, false);
if (intersects.length > 0) {
const point = intersects[0].point;
const normal = intersects[0].face.normal;
const position = new THREE.Vector3().copy(point).add(normal.multiplyScalar(0.5)).floor().addScalar(0.5);
if (event.button === 0) {
// Left-click to place a block
createPhysicalBlock(position.x, position.y, position.z);
} else if (event.button === 2) {
// Right-click to remove a block
const voxel = intersects[0].object;
scene.remove(voxel);
physicsWorld.removeBody(voxel.userData.body);
}
}
}
window.addEventListener('pointerdown', onPointerDown);
window.addEventListener('contextmenu', (event) => event.preventDefault());
9. Lighting and Environment
// Ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Adjust ambient light during day-night cycle
function updateAmbientLight() {
ambientLight.intensity = 0.2 + (sun.intensity * 0.8);
}
10. Event Handling
// Handle window resize events
window.addEventListener('resize', onWindowResize);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
11. Animation Loop
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
// Update physics world
physicsWorld.step(1 / 60, deltaTime, 3);
// Update player movement
updatePlayer(deltaTime);
// Update camera position and rotation
updateCameraPosition();
// Load and unload chunks based on player's position
loadChunks(playerBody.position);
// Update day-night cycle
updateDayNightCycle(deltaTime);
updateAmbientLight();
// Render the scene
renderer.render(scene, camera);
}
animate();
12. Helper Functions
// Update player function
function updatePlayer(deltaTime) {
const forward = new CANNON.Vec3(
-Math.sin(rotation.y),
0,
-Math.cos(rotation.y)
);
const right = new CANNON.Vec3(
Math.cos(rotation.y),
0,
-Math.sin(rotation.y)
);
const velocity = playerBody.velocity;
if (keysPressed['KeyW']) {
velocity.vadd(forward.scale(movementSpeed * deltaTime), velocity);
}
if (keysPressed['KeyS']) {
velocity.vsub(forward.scale(movementSpeed * deltaTime), velocity);
}
if (keysPressed['KeyA']) {
velocity.vsub(right.scale(movementSpeed * deltaTime), velocity);
}
if (keysPressed['KeyD']) {
velocity.vadd(right.scale(movementSpeed * deltaTime), velocity);
}
// Jumping
if (keysPressed['Space'] && isPlayerOnGround()) {
velocity.y = jumpSpeed;
}
}
// Check if player is on the ground
function isPlayerOnGround() {
const ray = new CANNON.Ray(playerBody.position, new CANNON.Vec3(0, -1, 0));
const result = new CANNON.RaycastResult();
ray.intersectWorld(physicsWorld, {
collisionFilterMask: -1,
skipBackfaces: true,
}, result);
return result.hasHit && result.distance <= 1.1;
}
13. Additional Features
- Smooth Camera Movement: The camera smoothly follows the player position and rotation, providing a better user experience.
- Adjustable Day-Night Cycle: Press the
J key along with the ArrowUp or ArrowDown keys to adjust the day-night cycle duration for testing purposes.
- Visual Indicators: The sun and moon are represented by meshes, moving across the sky to indicate the time of day.
Notes
- Ensure all necessary libraries (Three.js, Cannon.js, SimplexNoise, etc.) are properly imported or included in your project.
- Remember to call
preventDefault() on events where necessary to prevent unwanted browser behavior.
- This implementation focuses on key concepts and may require further refinement for a production environment.
- For block placement and removal, ensure that the blocks are added to and removed from the physics world correctly to maintain performance.
Feel free to customize and expand upon this code to suit your specific project needs. If you have any questions or need further assistance, don't hesitate to ask!