Создам для вас полноценную 3D игру в стиле Minecraft на HTML5 с использованием Three.js. Это будет включать генерацию мира, размещение/удаление блоков, управление от первого лица и базовую физику.
html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Minecraft 3D</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background: #87CEEB;
font-family: Arial, sans-serif;
}
#gameContainer {
position: relative;
width: 100vw;
height: 100vh;
}
#ui {
position: absolute;
top: 10px;
left: 10px;
color: white;
z-index: 100;
background: rgba(0,0,0,0.5);
padding: 10px;
border-radius: 5px;
}
#crosshair {
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
margin: -10px 0 0 -10px;
z-index: 100;
}
#crosshair::before,
#crosshair::after {
content: '';
position: absolute;
background: white;
}
#crosshair::before {
width: 2px;
height: 20px;
left: 9px;
top: 0;
}
#crosshair::after {
width: 20px;
height: 2px;
left: 0;
top: 9px;
}
#inventory {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 5px;
z-index: 100;
}
.inventory-slot {
width: 50px;
height: 50px;
background: rgba(0,0,0,0.7);
border: 2px solid #666;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 12px;
cursor: pointer;
}
.inventory-slot.active {
border-color: white;
}
#instructions {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.8);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
z-index: 200;
}
</style>
</head>
<body>
<div id="gameContainer">
<div id="ui">
<div>FPS: <span id="fps">0</span></div>
<div>Позиция: <span id="position">0, 0, 0</span></div>
<div>Блоков: <span id="blockCount">0</span></div>
</div>
<div id="crosshair"></div>
<div id="inventory">
<div class="inventory-slot active" data-block="grass">Трава</div>
<div class="inventory-slot" data-block="stone">Камень</div>
<div class="inventory-slot" data-block="wood">Дерево</div>
<div class="inventory-slot" data-block="dirt">Земля</div>
</div>
<div id="instructions">
<h3>Управление:</h3>
<p>WASD - движение</p>
<p>Мышь - обзор</p>
<p>ЛКМ - удалить блок</p>
<p>ПКМ - поставить блок</p>
<p>1-4 - выбор блока</p>
<p>Пробел - прыжок</p>
<p><button onclick="startGame()">Начать игру</button></p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
// Глобальные переменры
let scene, camera, renderer, controls;
let world = {};
let player = {
position: new THREE.Vector3(0, 10, 0),
velocity: new THREE.Vector3(0, 0, 0),
onGround: false,
selectedBlock: 'grass'
};
let keys = {};
let mouse = { x: 0, y: 0 };
let raycaster = new THREE.Raycaster();
let isPointerLocked = false;
// Материалы блоков
const blockMaterials = {
grass: new THREE.MeshLambertMaterial({ color: 0x4CAF50 }),
stone: new THREE.MeshLambertMaterial({ color: 0x808080 }),
wood: new THREE.MeshLambertMaterial({ color: 0x8B4513 }),
dirt: new THREE.MeshLambertMaterial({ color: 0x8B4513 })
};
// Геометрия блока
const blockGeometry = new THREE.BoxGeometry(1, 1, 1);
function startGame() {
document.getElementById('instructions').style.display = 'none';
initGame();
requestPointerLock();
}
function initGame() {
// Создание сцены
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x87CEEB, 50, 200);
// Создание камеры
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.copy(player.position);
// Создание рендерера
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x87CEEB);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('gameContainer').appendChild(renderer.domElement);
// Освещение
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(50, 50, 50);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
scene.add(directionalLight);
// Генерация мира
generateWorld();
// Обработчики событий
setupEventListeners();
// Запуск игрового цикла
gameLoop();
}
function generateWorld() {
const size = 50;
const height = 10;
for (let x = -size; x < size; x++) {
for (let z = -size; z < size; z++) {
// Простая генерация высоты с шумом
const h = Math.floor(Math.sin(x * 0.1) * Math.cos(z * 0.1) * 3 + height);
for (let y = 0; y < h; y++) {
let blockType = 'stone';
if (y === h - 1) blockType = 'grass';
else if (y > h - 4) blockType = 'dirt';
createBlock(x, y, z, blockType);
}
// Случайные деревья
if (Math.random() < 0.02 && h > 5) {
for (let y = h; y < h + 5; y++) {
createBlock(x, y, z, 'wood');
}
}
}
}
}
function createBlock(x, y, z, type) {
const key = `${x},${y},${z}`;
if (world[key]) return;
const mesh = new THREE.Mesh(blockGeometry, blockMaterials[type]);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData = { type: type, x: x, y: y, z: z };
scene.add(mesh);
world[key] = mesh;
}
function removeBlock(x, y, z) {
const key = `${x},${y},${z}`;
if (world[key]) {
scene.remove(world[key]);
delete world[key];
}
}
function setupEventListeners() {
// Клавиатура
document.addEventListener('keydown', (e) => {
keys[e.code] = true;
// Выбор блоков
if (e.code >= 'Digit1' && e.code <= 'Digit4') {
const blockTypes = ['grass', 'stone', 'wood', 'dirt'];
const index = parseInt(e.code.slice(-1)) - 1;
player.selectedBlock = blockTypes[index];
updateInventoryUI();
}
});
document.addEventListener('keyup', (e) => {
keys[e.code] = false;
});
// Мышь
document.addEventListener('mousemove', (e) => {
if (!isPointerLocked) return;
const sensitivity = 0.002;
camera.rotation.y -= e.movementX * sensitivity;
camera.rotation.x -= e.movementY * sensitivity;
camera.rotation.x = Math.max(-Math.PI/2, Math.min(Math.PI/2, camera.rotation.x));
});
document.addEventListener('mousedown', (e) => {
if (!isPointerLocked) return;
const intersect = getIntersection();
if (!intersect) return;
if (e.button === 0) { // ЛКМ - удаление
const block = intersect.object;
removeBlock(block.userData.x, block.userData.y, block.userData.z);
} else if (e.button === 2) { // ПКМ - размещение
const face = intersect.face;
const normal = face.normal;
const block = intersect.object;
const newX = block.userData.x + normal.x;
const newY = block.userData.y + normal.y;
const newZ = block.userData.z + normal.z;
// Проверка, что блок не пересекается с игроком
const playerPos = player.position;
const distance = Math.sqrt(
Math.pow(newX - playerPos.x, 2) +
Math.pow(newY - playerPos.y, 2) +
Math.pow(newZ - playerPos.z, 2)
);
if (distance > 1.5) {
createBlock(newX, newY, newZ, player.selectedBlock);
}
}
});
document.addEventListener('contextmenu', (e) => e.preventDefault());
// Инвентарь
document.querySelectorAll('.inventory-slot').forEach((slot, index) => {
slot.addEventListener('click', () => {
player.selectedBlock = slot.dataset.block;
updateInventoryUI();
});
});
// Изменение размера окна
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
}
function requestPointerLock() {
renderer.domElement.requestPointerLock();
document.addEventListener('pointerlockchange', () => {
isPointerLocked = document.pointerLockElement === renderer.domElement;
});
}
function getIntersection() {
raycaster.setFromCamera({ x: 0, y: 0 }, camera);
const intersects = raycaster.intersectObjects(Object.values(world));
return intersects.length > 0 ? intersects[0] : null;
}
function updateInventoryUI() {
document.querySelectorAll('.inventory-slot').forEach(slot => {
slot.classList.toggle('active', slot.dataset.block === player.selectedBlock);
});
}
function updatePlayer() {
const speed = 0.1;
const jumpPower = 0.15;
const gravity = -0.01;
// Движение
const direction = new THREE.Vector3();
if (keys['KeyW']) direction.z -= 1;
if (keys['KeyS']) direction.z += 1;
if (keys['KeyA']) direction.x -= 1;
if (keys['KeyD']) direction.x += 1;
if (direction.length() > 0) {
direction.normalize();
direction.applyQuaternion(camera.quaternion);
direction.y = 0;
direction.normalize();
player.velocity.x += direction.x * speed;
player.velocity.z += direction.z * speed;
}
// Прыжок
if (keys['Space'] && player.onGround) {
player.velocity.y = jumpPower;
player.onGround = false;
}
// Гравитация
player.velocity.y += gravity;
// Применение скорости
player.position.add(player.velocity);
// Проверка коллизий
checkCollisions();
// Затухание скорости
player.velocity.x *= 0.8;
player.velocity.z *= 0.8;
// Обновление позиции камеры
camera.position.copy(player.position);
}
function checkCollisions() {
const playerBox = new THREE.Box3(
new THREE.Vector3(
player.position.x - 0.3,
player.position.y - 1.8,
player.position.z - 0.3
),
new THREE.Vector3(
player.position.x + 0.3,
player.position.y + 0.2,
player.position.z + 0.3
)
);
player.onGround = false;
for (let key in world) {
const block = world[key];
const blockBox = new THREE.Box3().setFromObject(block