Certainly! Let's work through your project step by step to create a 3D voxel-based world using Three.js and Cannon.js. Below, I'll provide guidance and code snippets to help you implement each requirement.
1. Setup Three.js Scene
Initialize the Scene, Camera, and Renderer:
// Import Three.js
import * as THREE from 'three';
// Create the scene
const scene = new THREE.Scene();
// Set the background color to sky blue
scene.background = new THREE.Color(0x87ceeb);
// 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
);
// Position the camera (adjust as needed)
camera.position.set(0, 10, 20);
// Create the renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
// Append the renderer canvas to the DOM
document.body.appendChild(renderer.domElement);
2. Initialize Cannon.js Physics World
// Import Cannon.js
import * as CANNON from 'cannon-es'; // Use 'cannon-es' for modern ES modules
// Create the physics world
const world = new CANNON.World({
gravity: new CANNON.Vec3(0, -9.82, 0), // Earth's gravity
});
// Define a default material with zero friction and restitution
const defaultMaterial = new CANNON.Material('default');
const defaultContactMaterial = new CANNON.ContactMaterial(
defaultMaterial,
defaultMaterial,
{
friction: 0.0,
restitution: 0.0,
}
);
world.defaultContactMaterial = defaultContactMaterial;
3. Chunk Management for Terrain
Chunk Parameters:
const chunkSize = 16; // Size of each chunk
const renderDistance = 3; // Number of chunks to load around the player
Utility Functions:
// Function to calculate chunk ID based on position
function getChunkID(x, z) {
const chunkX = Math.floor(x / chunkSize);
const chunkZ = Math.floor(z / chunkSize);
return `${chunkX},${chunkZ}`;
}
// Store loaded chunks
const chunks = {};
Create Ground Chunks:
function createGroundChunk(chunkX, chunkZ) {
const width = chunkSize;
const depth = chunkSize;
// Generate height data (flat terrain for simplicity)
const heights = [];
for (let i = 0; i <= width; i++) {
heights[i] = [];
for (let j = 0; j <= depth; j++) {
heights[i][j] = 0; // Flat terrain; you can use noise for variation
}
}
// Create the heightfield shape
const hfShape = new CANNON.Heightfield(heights, {
elementSize: 1,
});
// Create the physics body
const hfBody = new CANNON.Body({ mass: 0 });
hfBody.addShape(hfShape, new CANNON.Vec3(
chunkX * chunkSize,
0,
chunkZ * chunkSize
));
world.addBody(hfBody);
// Create the visual mesh
const geometry = new THREE.PlaneGeometry(
width,
depth,
width,
depth
);
geometry.rotateX(-Math.PI / 2);
const material = new THREE.MeshStandardMaterial({ color: 0x228B22 });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(
chunkX * chunkSize + width / 2,
0,
chunkZ * chunkSize + depth / 2
);
scene.add(mesh);
// Store the chunk
const chunkID = `${chunkX},${chunkZ}`;
chunks[chunkID] = { mesh, hfBody };
}
Load and Unload Chunks:
function loadChunks(playerPosition) {
const currentChunkX = Math.floor(playerPosition.x / chunkSize);
const currentChunkZ = Math.floor(playerPosition.z / chunkSize);
// Calculate which chunks should be loaded
for (let i = -renderDistance; i <= renderDistance; i++) {
for (let j = -renderDistance; j <= renderDistance; j++) {
const chunkX = currentChunkX + i;
const chunkZ = currentChunkZ + j;
const chunkID = `${chunkX},${chunkZ}`;
if (!chunks[chunkID]) {
createGroundChunk(chunkX, chunkZ);
}
}
}
// Unload chunks that are out of range
for (const chunkID in chunks) {
const [chunkX, chunkZ] = chunkID.split(',').map(Number);
if (
Math.abs(chunkX - currentChunkX) > renderDistance ||
Math.abs(chunkZ - currentChunkZ) > renderDistance
) {
// Remove from physics world
world.removeBody(chunks[chunkID].hfBody);
// Remove from scene
scene.remove(chunks[chunkID].mesh);
// Delete from chunks object
delete chunks[chunkID];
}
}
}
4. Player Setup
// Create the player physics body
const playerRadius = 0.5;
const playerBody = new CANNON.Body({
mass: 1,
shape: new CANNON.Sphere(playerRadius),
fixedRotation: true,
material: defaultMaterial,
});
playerBody.position.set(0, 5, 0); // Start position
world.addBody(playerBody);
// Create a dummy Three.js mesh (invisible)
const playerMesh = new THREE.Mesh(
new THREE.SphereGeometry(playerRadius),
new THREE.MeshBasicMaterial({ visible: false })
);
scene.add(playerMesh);
5. Controls and Movement
Keyboard Input Handling:
const keysPressed = {};
window.addEventListener('keydown', (event) => {
keysPressed[event.code] = true;
});
window.addEventListener('keyup', (event) => {
keysPressed[event.code] = false;
});
Player Movement Logic:
// Movement parameters
const moveSpeed = 5; // Units per second
const jumpVelocity = 5; // Initial jump velocity
function updatePlayer(deltaTime) {
// Calculate forward and right vectors
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3();
right.crossVectors(camera.up, forward).normalize();
// Initialize movement vector
const moveVector = new CANNON.Vec3();
// Apply movement based on keys
if (keysPressed['KeyW']) {
moveVector.vadd(forward.multiplyScalar(moveSpeed * deltaTime), moveVector);
}
if (keysPressed['KeyS']) {
moveVector.vadd(forward.multiplyScalar(-moveSpeed * deltaTime), moveVector);
}
if (keysPressed['KeyA']) {
moveVector.vadd(right.multiplyScalar(-moveSpeed * deltaTime), moveVector);
}
if (keysPressed['KeyD']) {
moveVector.vadd(right.multiplyScalar(moveSpeed * deltaTime), moveVector);
}
// Apply the movement to the player body
playerBody.velocity.x = moveVector.x;
playerBody.velocity.z = moveVector.z;
// Jumping
if (keysPressed['Space'] && isPlayerOnGround()) {
playerBody.velocity.y = jumpVelocity;
}
// Update the Three.js mesh to match the physics body
playerMesh.position.copy(playerBody.position);
}
Function to Check if Player is on the Ground:
function isPlayerOnGround() {
const ray = new CANNON.Ray(playerBody.position, new CANNON.Vec3(0, -1, 0));
const rayResult = new CANNON.RaycastResult();
const distance = playerRadius + 0.1; // Slight offset
ray.intersectWorld(world, {
result: rayResult,
skipBackfaces: true,
collisionFilterMask: 1,
});
return rayResult.hasHit && rayResult.distance <= distance;
}
Camera Rotation Controls:
let rotation = {
x: 0, // Vertical rotation
y: 0, // Horizontal rotation
};
const rotationSpeed = 0.002; // Adjust for sensitivity
window.addEventListener('mousemove', (event) => {
if (document.pointerLockElement === renderer.domElement) {
rotation.y -= event.movementX * rotationSpeed;
rotation.x -= event.movementY * rotationSpeed;
// Limit vertical rotation to prevent flipping
rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, rotation.x));
}
});
// Request pointer lock on click
renderer.domElement.addEventListener('click', () => {
renderer.domElement.requestPointerLock();
});
Update Camera Position and Rotation:
function updateCamera() {
// Calculate the camera offset from the player
const cameraOffset = new THREE.Vector3(0, 1.6, 0); // Adjust for camera height
const cameraPosition = new THREE.Vector3().copy(playerMesh.position).add(cameraOffset);
camera.position.copy(cameraPosition);
// Set the camera rotation
camera.rotation.set(rotation.x, rotation.y, 0);
}
6. Day-Night Cycle
Variables and Objects:
let time = 0; // Time in seconds
const dayDuration = 60; // Duration of a full day in seconds
// Sun and Moon
const sun = new THREE.DirectionalLight(0xffffff, 1);
scene.add(sun);
const moon = new THREE.DirectionalLight(0x9999ff, 0.1);
scene.add(moon);
// Sun and moon meshes (for visual representation)
const sunMesh = new THREE.Mesh(
new THREE.SphereGeometry(5),
new THREE.MeshBasicMaterial({ color: 0xffff00 })
);
scene.add(sunMesh);
const moonMesh = new THREE.Mesh(
new THREE.SphereGeometry(3),
new THREE.MeshBasicMaterial({ color: 0xaaaaaa })
);
scene.add(moonMesh);
Update Day-Night Cycle Function:
function updateDayNightCycle(deltaTime) {
time += deltaTime;
const angle = (time / dayDuration) * Math.PI * 2; // Full rotation over dayDuration
// Sun position
sun.position.set(
Math.cos(angle) * 100,
Math.sin(angle) * 100,
0
);
sunMesh.position.copy(sun.position);
// Moon is opposite the sun
moon.position.set(
-Math.cos(angle) * 100,
-Math.sin(angle) * 100,
0
);
moonMesh.position.copy(moon.position);
// Adjust sun and moon intensity
sun.intensity = Math.max(0, Math.sin(angle));
moon.intensity = Math.max(0, -Math.sin(angle));
// Sky color transition
const skyColor = new THREE.Color();
if (sun.intensity > 0) {
// Daytime sky
skyColor.lerpColors(new THREE.Color(0x87ceeb), new THREE.Color(0x000000), 1 - sun.intensity);
} else {
// Nighttime sky
skyColor.set(0x000022);
}
scene.background = skyColor;
// Show/hide stars based on time
if (moon.intensity > 0.5) {
// Show stars
stars.visible = true;
} else {
stars.visible = false;
}
}
Adjustable Day-Night Cycle Duration with Keyboard Input:
window.addEventListener('keydown', (event) => {
if (event.code === 'KeyJ') {
if (keysPressed['ArrowUp']) {
dayDuration = Math.max(10, dayDuration - 10);
} else if (keysPressed['ArrowDown']) {
dayDuration += 10;
}
}
});
7. Block Placement and Removal
Raycasting Setup:
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
Mouse Event Handling:
window.addEventListener('mousedown', (event) => {
// Calculate mouse position in normalized device coordinates
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
// Update the raycaster
raycaster.setFromCamera(mouse, camera);
// Check for intersections
const intersects = raycaster.intersectObjects(scene.children, true);
if (intersects.length > 0) {
const point = intersects[0].point;
const normal = intersects[0].face.normal;
if (event.button === 0) {
// Left-click to place a block
const position = point.clone().add(normal.multiplyScalar(0.5));
placeBlock(position);
} else if (event.button === 2) {
// Right-click to remove a block
removeBlock(intersects[0].object);
}
}
});
// Prevent context menu on right-click
window.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
Block Placement and Removal Functions:
const blocks = [];
function placeBlock(position) {
const blockSize = 1;
const geometry = new THREE.BoxGeometry(blockSize, blockSize, blockSize);
const material = new THREE.MeshStandardMaterial({ color: 0x8B4513 });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(
Math.round(position.x),
Math.round(position.y),
Math.round(position.z)
);
scene.add(mesh);
// Add to physics world
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.copy(mesh.position);
world.addBody(body);
blocks.push({ mesh, body });
}
function removeBlock(object) {
// Find the block
const block = blocks.find((b) => b.mesh === object);
if (block) {
// Remove from scene and physics world
scene.remove(block.mesh);
world.removeBody(block.body);
// Remove from blocks array
blocks.splice(blocks.indexOf(block), 1);
}
}
8. Lighting and Environment
Ambient Light and Directional Light:
// Ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Stars
const starGeometry = new THREE.BufferGeometry();
const starMaterial = new THREE.PointsMaterial({ color: 0xffffff });
const starVertices = [];
for (let i = 0; i < 1000; i++) {
starVertices.push(
(Math.random() - 0.5) * 2000,
(Math.random() - 0.5) * 2000,
(Math.random() - 0.5) * 2000
);
}
starGeometry.setAttribute(
'position',
new THREE.Float32BufferAttribute(starVertices, 3)
);
const stars = new THREE.Points(starGeometry, starMaterial);
stars.visible = false;
scene.add(stars);
Adjust Ambient Light During Day-Night Cycle:
In the updateDayNightCycle function, adjust ambient light intensity:
ambientLight.intensity = 0.25 + sun.intensity * 0.75;
9. Event Handling
Window Resize Handling:
window.addEventListener('resize', onWindowResize);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
10. Animation Loop
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
// Step the physics world
world.step(1 / 60, deltaTime, 3);
// Update player
updatePlayer(deltaTime);
// Update camera
updateCamera();
// Load and unload chunks
loadChunks(playerBody.position);
// Update day-night cycle
updateDayNightCycle(deltaTime);
// Render the scene
renderer.render(scene, camera);
}
animate();
11. Optimizations
- Use efficient data structures like objects or maps for managing chunks and blocks.
- Limit the number of dynamic objects; set chunks and blocks to mass: 0 to make them static.
- Use instanced meshes if you have many similar objects to reduce draw calls.
12. Physics and Collision
- Ensure that the player's sphere shape is appropriate for interaction with heightfields and blocks.
- Adjust the physics timestep (
world.step) parameters for stability.
- Use raycasting in physics to detect if the player is on the ground for jumping logic.
13. Additional Features
-
Smooth Movement: You might want to implement damping on the player's movement to make it feel smoother.
// Apply damping
playerBody.velocity.x *= 0.9;
playerBody.velocity.z *= 0.9;
-
Visual Indicators: The sun and moon meshes provide a visual indication of the time of day.
Conclusion
By following these steps, you should have a basic voxel-based world with player movement, terrain generation, a day-night cycle, and block interaction mechanics. This provides a foundation that you can expand upon to add more features, such as improved terrain generation algorithms, textures, or additional gameplay mechanics.
Note: Be sure to include the necessary imports and dependencies in your project, such as Three.js, Cannon.js (or cannon-es), and any loaders or controls you might use. Additionally, consider modularizing your code by dividing it into separate scripts or classes for better organization and maintainability.