Adding endless terrain to your simple Minecraft clone involves dynamically generating and managing blocks around the player's position as they move. This typically involves dividing the world into manageable sections called "chunks" and loading or unloading these chunks based on the player's current location. Below is the modified version of your code with comments explaining the new additions and changes.
Key Changes:
-
Chunk System: The world is divided into chunks of a specified size (e.g., 16x16 blocks). This helps manage and optimize the loading and unloading of blocks.
-
Dynamic Terrain Generation: As the player moves, new chunks are generated around the player while chunks far away are removed to ensure the terrain appears endless.
-
Performance Optimization: Using InstancedMesh can further optimize performance, but for simplicity, this example continues using regular Mesh objects.
-
Procedural Terrain: For variety, you can integrate procedural generation algorithms (like Perlin noise) to create varied terrains. In this example, the terrain is kept flat for simplicity.
Complete Modified Code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Minecraft Clone with Endless Terrain</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100vw;
height: 100vh;
display: block;
}
#instructions {
position: fixed;
top: 10px;
left: 10px;
color: white;
font-family: Arial, sans-serif;
background: rgba(0,0,0,0.5);
padding: 10px;
border-radius: 5px;
z-index: 1;
}
</style>
</head>
<body>
<div id="instructions">
WASD - Move<br>
SPACE - Jump<br>
LEFT CLICK - Remove block<br>
RIGHT CLICK - Place block<br>
MOUSE - Look around
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
// Initialize Three.js
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB); // Blue sky
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Define chunk size and view distance
const CHUNK_SIZE = 16;
const VIEW_DISTANCE = 3; // Number of chunks to load in each direction
// Store loaded chunks
const loadedChunks = new Map();
// Create block geometry and material
const blockGeometry = new THREE.BoxGeometry(1, 1, 1);
const blockMaterial = new THREE.MeshPhongMaterial({
color: 0x2E8B57, // Sea green color for blocks
specular: 0x444444,
shininess: 30
});
// Add lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 20, 10);
scene.add(directionalLight);
// Group to hold all blocks
const blocks = new THREE.Group();
scene.add(blocks);
// Function to generate a chunk at given chunk coordinates
function generateChunk(chunkX, chunkZ) {
const chunkKey = `${chunkX}_${chunkZ}`;
if (loadedChunks.has(chunkKey)) return; // Chunk already loaded
const chunkGroup = new THREE.Group();
for (let x = 0; x < CHUNK_SIZE; x++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const block = new THREE.Mesh(blockGeometry, blockMaterial);
block.position.set(
chunkX * CHUNK_SIZE + x,
-1, // Flat terrain at y = -1
chunkZ * CHUNK_SIZE + z
);
chunkGroup.add(block);
}
}
blocks.add(chunkGroup);
loadedChunks.set(chunkKey, chunkGroup);
}
// Function to update loaded chunks based on player position
function updateChunks(playerX, playerZ) {
const currentChunkX = Math.floor(playerX / CHUNK_SIZE);
const currentChunkZ = Math.floor(playerZ / CHUNK_SIZE);
// Determine which chunks should be loaded
for (let x = currentChunkX - VIEW_DISTANCE; x <= currentChunkX + VIEW_DISTANCE; x++) {
for (let z = currentChunkZ - VIEW_DISTANCE; z <= currentChunkZ + VIEW_DISTANCE; z++) {
generateChunk(x, z);
}
}
// Remove chunks that are outside the view distance
for (let key of loadedChunks.keys()) {
const [chunkX, chunkZ] = key.split('_').map(Number);
if (Math.abs(chunkX - currentChunkX) > VIEW_DISTANCE || Math.abs(chunkZ - currentChunkZ) > VIEW_DISTANCE) {
const chunk = loadedChunks.get(key);
blocks.remove(chunk);
loadedChunks.delete(key);
}
}
}
// Initial chunks
const initialPlayerX = player?.position?.x || 0;
const initialPlayerZ = player?.position?.z || 0;
updateChunks(initialPlayerX, initialPlayerZ);
// Player movement variables
const player = {
position: new THREE.Vector3(0, 0, 0),
velocity: new THREE.Vector3(),
onGround: false,
speed: 0.1,
jumpForce: 0.2
};
// Camera controls
let pitch = 0;
let yaw = 0;
let mouseDown = false;
// Movement controls
const keys = {};
// Raycaster for block placement/removal
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Block placement helper function
function placeBlock(intersectPoint, normal) {
const position = new THREE.Vector3()
.copy(intersectPoint)
.add(normal)
.round();
// Check if block already exists at position
const blockExists = blocks.children.some(chunk =>
chunk.children.some(block =>
block.position.x === position.x &&
block.position.y === position.y &&
block.position.z === position.z
)
);
if (!blockExists) {
const block = new THREE.Mesh(blockGeometry, blockMaterial);
block.position.copy(position);
blocks.add(block);
}
}
// Event listeners
document.addEventListener('keydown', (e) => {
keys[e.key.toLowerCase()] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.key.toLowerCase()] = false;
});
document.addEventListener('mousedown', (e) => {
if (document.pointerLockElement === document.body) {
raycaster.setFromCamera(new THREE.Vector2(0, 0), camera);
const intersects = raycaster.intersectObjects(blocks.children, true);
if (intersects.length > 0) {
if (e.button === 0) { // Left click - remove block
const intersectedBlock = intersects[0].object;
blocks.remove(intersectedBlock);
// Optionally, also remove from chunk group
// This depends on how you structure your chunks
} else if (e.button === 2) { // Right click - add block
const intersect = intersects[0];
placeBlock(intersect.point, intersect.face.normal);
}
}
}
});
document.addEventListener('mouseup', () => mouseDown = false);
document.addEventListener('mousemove', (e) => {
if (document.pointerLockElement === document.body) {
yaw -= e.movementX * 0.002;
pitch -= e.movementY * 0.002;
pitch = Math.max(-Math.PI/2, Math.min(Math.PI/2, pitch));
}
});
document.addEventListener('contextmenu', (e) => e.preventDefault());
renderer.domElement.addEventListener('click', () => {
document.body.requestPointerLock();
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Handle movement
let moved = false;
if (keys['w']) {
player.position.x -= Math.sin(yaw) * player.speed;
player.position.z -= Math.cos(yaw) * player.speed;
moved = true;
}
if (keys['s']) {
player.position.x += Math.sin(yaw) * player.speed;
player.position.z += Math.cos(yaw) * player.speed;
moved = true;
}
if (keys['a']) {
player.position.x -= Math.cos(yaw) * player.speed;
player.position.z += Math.sin(yaw) * player.speed;
moved = true;
}
if (keys['d']) {
player.position.x += Math.cos(yaw) * player.speed;
player.position.z -= Math.sin(yaw) * player.speed;
moved = true;
}
if (keys[' ']) {
if (player.onGround) {
player.velocity.y = player.jumpForce;
player.onGround = false;
}
}
// Apply gravity
if (!player.onGround) {
player.velocity.y -= 0.01;
}
player.position.y += player.velocity.y;
// Simple ground collision
if (player.position.y < 0) {
player.position.y = 0;
player.velocity.y = 0;
player.onGround = true;
}
// Update camera position and rotation
camera.position.copy(player.position);
camera.position.y += 1.6; // Eye height
camera.rotation.order = 'YXZ';
camera.rotation.y = yaw;
camera.rotation.x = pitch;
// Update chunks if player has moved to a new chunk
updateChunks(player.position.x, player.position.z);
renderer.render(scene, camera);
}
// Handle window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
animate();
</script>
</body>
</html>
Explanation of the Additions:
-
Chunk Management:
- Chunk Size and View Distance: Defined constants
CHUNK_SIZE and VIEW_DISTANCE to manage how large each chunk is and how many chunks are loaded around the player.
- Loaded Chunks Tracking: Utilized a
Map called loadedChunks to keep track of currently loaded chunks using a unique key format (chunkX_chunkZ).
-
Generating Chunks:
generateChunk Function: Creates a group of blocks for a specific chunk coordinate. This function checks if the chunk is already loaded to prevent duplicates.
- Initial Chunk Generation: Calls
updateChunks initially to load the starting chunks based on the player's initial position.
-
Updating Chunks Based on Player Movement:
updateChunks Function: Determines the current chunk based on the player's position and ensures that all chunks within the VIEW_DISTANCE are loaded. It also removes chunks that fall outside this range to optimize performance.
- Integration into Animation Loop: Calls
updateChunks within the animate function to continuously check and update chunks as the player moves.
-
Terrain Generation:
- Flat Terrain: For simplicity, the terrain is flat at
y = -1. You can enhance this by integrating procedural generation algorithms to create varied terrains.
- Block Placement and Removal: Adjusted the block placement and removal to work seamlessly with dynamically loaded chunks.
-
Performance Considerations:
- Grouping Blocks: Each chunk is grouped using
THREE.Group which can help in managing and rendering optimally.
- Potential Optimizations: For large-scale terrains, consider using
InstancedMesh to reduce the number of draw calls, or implement level of detail (LOD) techniques.
-
User Experience:
- Instructions Visibility: Added a higher
z-index to the instructions div to ensure it's always visible.
Further Enhancements:
- Procedural Terrain: Integrate algorithms like Perlin or Simplex noise to create varied and interesting terrains instead of a flat world.
- Performance Optimizations: Implement
InstancedMesh for rendering large numbers of similar objects more efficiently.
- Additional Features: Add features like different block types, more complex interactions, inventory systems, or multiplayer support.
- Collision Detection: Improve collision detection to prevent the player from passing through blocks.
- Smooth Terrain Generation: Implement smooth transitions between chunks and handle corner cases where chunks overlap or have different heights.
This modified code provides a foundational structure for an endless terrain system in your Minecraft clone. You can build upon this foundation to add more complexity and features as needed.