Creating a fully functional Minecraft-like game is a complex task that typically involves advanced 3D rendering, physics, and extensive game logic. However, I can provide you with a simplified version using the Three.js library, which allows for easier 3D rendering in the browser. This example will include:
- A basic block-based world.
- First-person controls for movement and camera rotation.
- Ability to place blocks with the right mouse button.
- Ability to remove blocks with the left mouse button.
- Jumping functionality with the space bar.
Note: This is a simplified version and serves as a foundation. For a more comprehensive game, additional features and optimizations would be necessary.
Here's the complete HTML, CSS, and JavaScript code in one document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Minecraft-like Game</title>
<style>
body {
margin: 0;
overflow: hidden;
}
#blockMenu {
position: absolute;
top: 10px;
left: 10px;
z-index: 100;
background: rgba(255,255,255,0.8);
padding: 10px;
border-radius: 5px;
}
#blockMenu span {
margin-right: 10px;
cursor: pointer;
}
#instructions {
position: absolute;
top: 50%;
width: 100%;
text-align: center;
color: white;
font-family: Arial, sans-serif;
font-size: 24px;
display: none;
z-index: 100;
}
</style>
</head>
<body>
<div id="instructions">
Click to Play<br>
Use WASD to move, Space to jump,<br>
Mouse to look around,<br>
Left-click to remove blocks, Right-click to add blocks.
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.150.1/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.150.1/examples/js/controls/PointerLockControls.js"></script>
<script>
let scene, camera, renderer, controls;
let raycaster;
const objects = [];
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
let canJump = false;
let velocity = new THREE.Vector3();
let direction = new THREE.Vector3();
let prevTime = performance.now();
init();
animate();
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87ceeb); // Sky blue
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Light
const light = new THREE.HemisphereLight(0xffffff, 0x444444);
light.position.set(0, 200, 0);
scene.add(light);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(0, 200, 100);
directionalLight.castShadow = true;
directionalLight.shadow.camera.top = 180;
directionalLight.shadow.camera.bottom = -100;
directionalLight.shadow.camera.left = -120;
directionalLight.shadow.camera.right = 120;
scene.add(directionalLight);
// Ground
const groundGeometry = new THREE.BoxGeometry(1000, 1, 1000);
const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x228B22 }); // Forest green
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.receiveShadow = true;
scene.add(ground);
objects.push(ground);
// Simple blocks (a few for demonstration)
const blockGeometry = new THREE.BoxGeometry(1, 1, 1);
const blockMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 }); // Brown
for (let i = -10; i <= 10; i++) {
for (let j = -10; j <= 10; j++) {
const block = new THREE.Mesh(blockGeometry, blockMaterial);
block.position.set(i, 0.5, j);
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
objects.push(block);
}
}
// Controls
controls = new THREE.PointerLockControls(camera, document.body);
const instructions = document.getElementById('instructions');
instructions.style.display = 'block';
instructions.addEventListener('click', function () {
controls.lock();
}, false);
controls.addEventListener('lock', function () {
instructions.style.display = 'none';
});
controls.addEventListener('unlock', function () {
instructions.style.display = 'block';
});
scene.add(controls.getObject());
const onKeyDown = function (event) {
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
moveForward = true;
break;
case 'ArrowLeft':
case 'KeyA':
moveLeft = true;
break;
case 'ArrowDown':
case 'KeyS':
moveBackward = true;
break;
case 'ArrowRight':
case 'KeyD':
moveRight = true;
break;
case 'Space':
if (canJump === true) velocity.y += 350;
canJump = false;
break;
}
};
const onKeyUp = function (event) {
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
moveForward = false;
break;
case 'ArrowLeft':
case 'KeyA':
moveLeft = false;
break;
case 'ArrowDown':
case 'KeyS':
moveBackward = false;
break;
case 'ArrowRight':
case 'KeyD':
moveRight = false;
break;
}
};
document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('keyup', onKeyUp, false);
// Raycaster for interactions
raycaster = new THREE.Raycaster();
// Mouse events
document.addEventListener('mousedown', onMouseDown, false);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onMouseDown(event) {
if (!controls.isLocked) return;
event.preventDefault();
const mouse = new THREE.Vector2();
mouse.x = 0;
mouse.y = 0;
if (event.clientX !== undefined && event.clientY !== undefined) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
}
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(objects, false);
if (intersects.length > 0) {
const intersect = intersects[0];
const distance = intersect.distance;
const point = intersect.point;
const normal = intersect.face.normal;
if (event.button === 0) {
// Left-click to remove block
if (intersect.object !== objects[0]) { // Don't remove ground
scene.remove(intersect.object);
const index = objects.indexOf(intersect.object);
if (index > -1) objects.splice(index, 1);
}
} else if (event.button === 2) {
// Right-click to add block
const blockGeometry = new THREE.BoxGeometry(1, 1, 1);
const blockMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
const block = new THREE.Mesh(blockGeometry, blockMaterial);
block.position.copy(point).add(normal);
block.position.divideScalar(1).floor().multiplyScalar(1).addScalar(0.5);
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
objects.push(block);
}
}
}
function animate() {
requestAnimationFrame(animate);
if (controls.isLocked === true) {
const time = performance.now();
const delta = (time - prevTime) / 1000;
velocity.x -= velocity.x * 10.0 * delta;
velocity.z -= velocity.z * 10.0 * delta;
velocity.y -= 9.8 * 100.0 * delta; // Gravity
direction.z = Number(moveForward) - Number(moveBackward);
direction.x = Number(moveRight) - Number(moveLeft);
direction.normalize(); // this ensures consistent movements in all directions
if (moveForward || moveBackward) velocity.z -= direction.z * 400.0 * delta;
if (moveLeft || moveRight) velocity.x -= direction.x * 400.0 * delta;
controls.moveRight(- velocity.x * delta);
controls.moveForward(- velocity.z * delta);
controls.getObject().position.y += (velocity.y * delta); // new behavior
if (controls.getObject().position.y < 1.5) {
velocity.y = 0;
controls.getObject().position.y = 1.5;
canJump = true;
}
prevTime = time;
}
renderer.render(scene, camera);
}
// Prevent context menu on right-click
document.addEventListener('contextmenu', event => event.preventDefault());
</script>
</body>
</html>
Explanation of the Code
-
HTML Structure: The HTML is simple, with a div for instructions that appears when the game starts.
-
Styles: The CSS ensures that the canvas takes up the full screen and styles the instruction overlay.
-
Three.js Setup:
- Scene: Creates a scene with a sky-blue background.
- Camera: A perspective camera is set up for a first-person view.
- Renderer: The WebGL renderer renders the scene onto the canvas.
- Lighting: Hemisphere and directional lights are added to illuminate the scene.
- Ground: A large green box serves as the ground.
- Blocks: Brown boxes are added to create a simple blocky environment.
-
Controls:
- PointerLockControls: Allows the user to control the camera with the mouse (look around).
- Movement: WASD keys for movement and space bar for jumping.
- Physics: Basic gravity and collision detection with the ground.
-
Interactions:
- Raycaster: Determines where the user is looking to place or remove blocks.
- Mouse Events: Left-click removes a block; right-click adds a block adjacent to the targeted block.
-
Animation Loop: Continuously updates the scene, handles movement, and renders each frame.
-
Additional Features:
- Preventing Right-Click Menu: The context menu is disabled to allow right-click interactions within the game.
How to Use
-
Launch the Game: Open the HTML file in a modern web browser (like Chrome or Firefox).
-
Start Playing:
- Click on the screen to lock the pointer and start the game.
- Use the W, A, S, D keys to move forward, left, backward, and right, respectively.
- Press the Space bar to jump.
- Move the mouse to look around.
- Left-click to remove blocks.
- Right-click to add blocks.
-
Exit Pointer Lock: Press the Esc key to release the pointer and bring back the instructions.
Important Notes
- Performance: This is a basic implementation. Performance may decrease with a large number of blocks.
- Features: Features like inventory management, different block types, multiplayer, and advanced physics are not included.
- Enhancements: For a more sophisticated game, consider using additional libraries or engines, implementing chunk loading, optimizing rendering, and adding more game mechanics.
This should provide you with a foundational understanding and a starting point to build upon for creating a more feature-rich block-based game.