Spaces:
Running
Running
Update game.js
Browse files
game.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import * as THREE from 'three';
|
| 2 |
import * as CANNON from 'cannon-es';
|
| 3 |
-
//
|
| 4 |
-
// import CannonDebugger from 'cannon-es-debugger';
|
| 5 |
|
| 6 |
// --- DOM Elements ---
|
| 7 |
const sceneContainer = document.getElementById('scene-container');
|
|
@@ -13,39 +12,46 @@ const logElement = document.getElementById('log-display');
|
|
| 13 |
const ROOM_SIZE = 10;
|
| 14 |
const WALL_HEIGHT = 4;
|
| 15 |
const WALL_THICKNESS = 0.5;
|
| 16 |
-
const CAMERA_Y_OFFSET = 20;
|
| 17 |
-
const PLAYER_SPEED =
|
| 18 |
const PLAYER_RADIUS = 0.5;
|
| 19 |
-
const PLAYER_HEIGHT = 1.8;
|
|
|
|
|
|
|
| 20 |
const PROJECTILE_SPEED = 15;
|
| 21 |
const PROJECTILE_RADIUS = 0.2;
|
|
|
|
| 22 |
|
| 23 |
// --- Three.js Setup ---
|
| 24 |
let scene, camera, renderer;
|
| 25 |
let playerMesh;
|
| 26 |
const meshesToSync = [];
|
| 27 |
const projectiles = [];
|
| 28 |
-
let axesHelper;
|
| 29 |
|
| 30 |
// --- Physics Setup ---
|
| 31 |
let world;
|
| 32 |
let playerBody;
|
| 33 |
-
const physicsBodies = [];
|
| 34 |
-
let cannonDebugger = null;
|
| 35 |
|
| 36 |
// --- Game State ---
|
| 37 |
-
let gameState = {};
|
| 38 |
const keysPressed = {};
|
| 39 |
-
let gameLoopActive = false;
|
|
|
|
| 40 |
|
| 41 |
-
// --- Game Data (
|
| 42 |
const gameData = {
|
| 43 |
-
"0,0": { type: 'city', features: ['door_north', 'item_Key'], name: "City Square"},
|
| 44 |
-
"0,1": { type: 'forest', features: ['path_north', 'door_south', '
|
| 45 |
-
"0,2": { type: 'forest', features: ['path_south'], name: "Deep Forest"},
|
| 46 |
"1,1": { type: 'forest', features: ['river', 'path_west'], name: "River Bend" },
|
| 47 |
-
"-1,1": { type: 'ruins', features: ['path_east'
|
| 48 |
-
//
|
|
|
|
|
|
|
|
|
|
| 49 |
};
|
| 50 |
|
| 51 |
const itemsData = {
|
|
@@ -59,72 +65,114 @@ const monstersData = {
|
|
| 59 |
// ...
|
| 60 |
};
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
// --- Initialization ---
|
| 63 |
|
| 64 |
function init() {
|
| 65 |
-
console.log("Initializing Game
|
| 66 |
// Reset state cleanly
|
| 67 |
gameState = {
|
| 68 |
inventory: [],
|
| 69 |
stats: { hp: 30, maxHp: 30, strength: 7, wisdom: 5, courage: 6 },
|
| 70 |
-
position: { x: 0, z: 0 },
|
| 71 |
-
monsters: [],
|
| 72 |
-
items: [],
|
| 73 |
};
|
| 74 |
-
|
| 75 |
meshesToSync.length = 0;
|
| 76 |
projectiles.length = 0;
|
| 77 |
physicsBodies.length = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
initThreeJS();
|
| 81 |
initPhysics();
|
| 82 |
-
initPlayer(); //
|
| 83 |
-
generateMap(); //
|
| 84 |
setupInputListeners();
|
| 85 |
-
updateUI();
|
| 86 |
-
addLog("Welcome! Move
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
}
|
| 91 |
|
| 92 |
function initThreeJS() {
|
| 93 |
console.log("Initializing Three.js...");
|
| 94 |
scene = new THREE.Scene();
|
| 95 |
-
scene.background = new THREE.Color(
|
| 96 |
|
| 97 |
-
|
| 98 |
-
camera.
|
| 99 |
-
camera.
|
|
|
|
| 100 |
|
| 101 |
renderer = new THREE.WebGLRenderer({ antialias: true });
|
| 102 |
renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
|
| 103 |
renderer.shadowMap.enabled = true;
|
|
|
|
| 104 |
sceneContainer.appendChild(renderer.domElement);
|
| 105 |
|
| 106 |
// Lighting
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
dirLight.position.set(15, 25, 10); // Higher angle
|
| 111 |
dirLight.castShadow = true;
|
| 112 |
-
dirLight.shadow.mapSize.width =
|
| 113 |
-
dirLight.shadow.mapSize.height =
|
| 114 |
-
|
| 115 |
-
dirLight.shadow.camera.
|
| 116 |
-
|
| 117 |
-
dirLight.shadow.camera.left = -
|
| 118 |
-
dirLight.shadow.camera.right =
|
| 119 |
-
dirLight.shadow.camera.top =
|
| 120 |
-
dirLight.shadow.camera.bottom = -
|
| 121 |
-
|
| 122 |
scene.add(dirLight);
|
| 123 |
-
// scene.add(
|
| 124 |
|
| 125 |
// Axes Helper
|
| 126 |
-
axesHelper = new THREE.AxesHelper(ROOM_SIZE
|
| 127 |
-
axesHelper.position.set(0, 0.
|
| 128 |
scene.add(axesHelper);
|
| 129 |
console.log("Three.js Initialized.");
|
| 130 |
|
|
@@ -133,235 +181,671 @@ function initThreeJS() {
|
|
| 133 |
|
| 134 |
function initPhysics() {
|
| 135 |
console.log("Initializing Cannon-es...");
|
| 136 |
-
world = new CANNON.World({ gravity: new CANNON.Vec3(0, -
|
| 137 |
-
world.broadphase = new CANNON.SAPBroadphase(world);
|
| 138 |
-
world.allowSleep = true;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
// Ground plane
|
| 141 |
const groundShape = new CANNON.Plane();
|
| 142 |
-
const groundBody = new CANNON.Body({ mass: 0, material:
|
| 143 |
groundBody.addShape(groundShape);
|
| 144 |
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
|
| 145 |
world.addBody(groundBody);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
console.log("Physics World Initialized.");
|
| 147 |
|
| 148 |
-
// Optional: Physics Debugger
|
| 149 |
// try {
|
| 150 |
-
// cannonDebugger = new CannonDebugger(scene, world, {
|
| 151 |
-
// color: 0x00ff00, // Optional: specify color
|
| 152 |
-
// scale: 1.0, // Optional: scale
|
| 153 |
-
// });
|
| 154 |
// console.log("Cannon-es Debugger Initialized.");
|
| 155 |
-
// } catch (e) {
|
| 156 |
-
// console.error("Failed to initialize CannonDebugger. Did you include it?", e);
|
| 157 |
-
// }
|
| 158 |
}
|
| 159 |
|
| 160 |
-
// --- Primitive
|
| 161 |
-
function createPlayerMesh() { /* ... same
|
| 162 |
const group = new THREE.Group();
|
| 163 |
-
|
| 164 |
-
const
|
|
|
|
| 165 |
const body = new THREE.Mesh(bodyGeom, bodyMat);
|
| 166 |
-
body.position.y = PLAYER_RADIUS;
|
| 167 |
-
|
| 168 |
-
const headGeom = new THREE.SphereGeometry(PLAYER_RADIUS, 16, 16);
|
| 169 |
const head = new THREE.Mesh(headGeom, bodyMat);
|
| 170 |
-
head.position.y = PLAYER_HEIGHT - PLAYER_RADIUS;
|
| 171 |
-
head.castShadow = true;
|
| 172 |
group.add(body); group.add(head);
|
| 173 |
-
const noseGeom = new THREE.ConeGeometry(PLAYER_RADIUS * 0.3, PLAYER_RADIUS * 0.5,
|
| 174 |
const noseMat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
|
| 175 |
const nose = new THREE.Mesh(noseGeom, noseMat);
|
| 176 |
-
nose
|
| 177 |
-
nose.
|
|
|
|
| 178 |
group.add(nose);
|
|
|
|
| 179 |
return group;
|
| 180 |
-
|
| 181 |
-
function createSimpleMonsterMesh(modelType = 'capsule_green') { /* ... same
|
| 182 |
const group = new THREE.Group();
|
| 183 |
-
let color =
|
| 184 |
-
let
|
| 185 |
if (modelType === 'capsule_green') {
|
| 186 |
color = 0x00ff00;
|
| 187 |
-
mat = new THREE.MeshLambertMaterial({ color: color });
|
| 188 |
-
const bodyGeom = new THREE.CylinderGeometry(0.4, 0.4, 1.0,
|
| 189 |
-
const headGeom = new THREE.SphereGeometry(0.4,
|
| 190 |
const body = new THREE.Mesh(bodyGeom, mat);
|
| 191 |
const head = new THREE.Mesh(headGeom, mat);
|
| 192 |
body.position.y = 0.5; head.position.y = 1.0 + 0.4;
|
| 193 |
group.add(body); group.add(head);
|
| 194 |
-
} else { geom = new THREE.BoxGeometry(0.8, 1.2, 0.8);
|
| 195 |
group.traverse(child => { if (child.isMesh) child.castShadow = true; });
|
|
|
|
| 196 |
return group;
|
| 197 |
}
|
| 198 |
-
function createSimpleItemMesh(modelType = 'sphere_red') { /* ... same
|
| 199 |
-
let geom, mat; let color =
|
| 200 |
-
|
|
|
|
| 201 |
else if (modelType === 'box_gold') { color = 0xffd700; geom = new THREE.BoxGeometry(0.4, 0.4, 0.4); }
|
| 202 |
-
else { geom = new THREE.SphereGeometry(0.3,
|
| 203 |
-
|
| 204 |
-
const mesh = new THREE.Mesh(geom, mat);
|
|
|
|
|
|
|
| 205 |
return mesh;
|
| 206 |
}
|
| 207 |
-
function createProjectileMesh() { /* ... same
|
| 208 |
-
const geom = new THREE.SphereGeometry(PROJECTILE_RADIUS,
|
| 209 |
const mat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
|
| 210 |
const mesh = new THREE.Mesh(geom, mat);
|
| 211 |
return mesh;
|
| 212 |
}
|
| 213 |
-
// Shared Geometries / Materials for walls/floors
|
| 214 |
-
const floorGeometry = new THREE.PlaneGeometry(ROOM_SIZE, ROOM_SIZE);
|
| 215 |
-
const wallN SGeometry = new THREE.BoxGeometry(ROOM_SIZE, WALL_HEIGHT, WALL_THICKNESS);
|
| 216 |
-
const wallEWGeometry = new THREE.BoxGeometry(WALL_THICKNESS, WALL_HEIGHT, ROOM_SIZE);
|
| 217 |
-
const floorMaterials = {
|
| 218 |
-
city: new THREE.MeshLambertMaterial({ color: 0xdeb887 }),
|
| 219 |
-
forest: new THREE.MeshLambertMaterial({ color: 0x228B22 }),
|
| 220 |
-
cave: new THREE.MeshLambertMaterial({ color: 0x696969 }),
|
| 221 |
-
ruins: new THREE.MeshLambertMaterial({ color: 0x778899 }),
|
| 222 |
-
plains: new THREE.MeshLambertMaterial({ color: 0x90EE90 }),
|
| 223 |
-
default: new THREE.MeshLambertMaterial({ color: 0xaaaaaa })
|
| 224 |
-
};
|
| 225 |
-
const wallMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 });
|
| 226 |
-
|
| 227 |
// --- Player Setup ---
|
| 228 |
function initPlayer() {
|
| 229 |
console.log("Initializing Player...");
|
| 230 |
// Visual Mesh
|
| 231 |
playerMesh = createPlayerMesh();
|
| 232 |
-
// Start
|
| 233 |
-
playerMesh.position.set(0, PLAYER_HEIGHT, 0); // Adjust initial Y based on model pivot
|
| 234 |
scene.add(playerMesh);
|
| 235 |
console.log("Player mesh added to scene.");
|
| 236 |
|
| 237 |
-
// Physics Body
|
|
|
|
|
|
|
|
|
|
| 238 |
const playerShape = new CANNON.Sphere(PLAYER_RADIUS);
|
| 239 |
playerBody = new CANNON.Body({
|
| 240 |
-
mass: 70,
|
| 241 |
shape: playerShape,
|
| 242 |
-
position: new CANNON.Vec3(
|
| 243 |
-
linearDamping: 0.95,
|
| 244 |
-
angularDamping: 1.0,
|
| 245 |
-
material: new CANNON.Material("player") //
|
| 246 |
});
|
| 247 |
-
|
| 248 |
-
playerBody.allowSleep = false; // Player should always be active
|
| 249 |
-
|
| 250 |
playerBody.addEventListener("collide", handlePlayerCollision);
|
| 251 |
world.addBody(playerBody);
|
| 252 |
-
|
|
|
|
| 253 |
|
| 254 |
// Add to sync list
|
| 255 |
meshesToSync.push({ mesh: playerMesh, body: playerBody });
|
|
|
|
| 256 |
}
|
| 257 |
|
| 258 |
// --- Map Generation ---
|
| 259 |
function generateMap() {
|
| 260 |
console.log("Generating Map...");
|
| 261 |
-
const
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
const
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
}
|
| 333 |
-
} else if (feature.startsWith('monster_')) {
|
| 334 |
-
const monsterType = feature.substring(8); // e.g., monster_goblin -> goblin
|
| 335 |
-
if(monstersData[monsterType]) {
|
| 336 |
-
spawnMonster(monsterType, x, z);
|
| 337 |
-
} else {
|
| 338 |
-
console.warn(`Monster feature found but no data for: ${monsterType}`);
|
| 339 |
-
}
|
| 340 |
}
|
| 341 |
-
|
| 342 |
-
else if (feature === 'river') {
|
| 343 |
-
const riverMesh = createFeature(feature, x, z);
|
| 344 |
-
if (riverMesh) scene.add(riverMesh);
|
| 345 |
-
}
|
| 346 |
-
});
|
| 347 |
}
|
| 348 |
console.log("Map Generation Complete.");
|
| 349 |
}
|
| 350 |
|
| 351 |
-
function spawnItem(itemName, gridX, gridZ) {
|
| 352 |
const itemData = itemsData[itemName];
|
| 353 |
if (!itemData) return;
|
| 354 |
const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
|
| 355 |
const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
|
| 356 |
-
const y = PLAYER_RADIUS;
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
| 358 |
mesh.position.set(x, y, z);
|
| 359 |
mesh.userData = { type: 'item', name: itemName };
|
|
|
|
| 360 |
scene.add(mesh);
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
world.addBody(body);
|
| 365 |
-
|
|
|
|
|
|
|
| 366 |
physicsBodies.push(body);
|
| 367 |
-
console.log(`Spawned
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import * as THREE from 'three';
|
| 2 |
import * as CANNON from 'cannon-es';
|
| 3 |
+
// import CannonDebugger from 'cannon-es-debugger'; // Keep commented unless debugging physics visually
|
|
|
|
| 4 |
|
| 5 |
// --- DOM Elements ---
|
| 6 |
const sceneContainer = document.getElementById('scene-container');
|
|
|
|
| 12 |
const ROOM_SIZE = 10;
|
| 13 |
const WALL_HEIGHT = 4;
|
| 14 |
const WALL_THICKNESS = 0.5;
|
| 15 |
+
const CAMERA_Y_OFFSET = 20;
|
| 16 |
+
const PLAYER_SPEED = 6; // Slightly faster
|
| 17 |
const PLAYER_RADIUS = 0.5;
|
| 18 |
+
const PLAYER_HEIGHT = 1.8; // Visual height
|
| 19 |
+
const PLAYER_PHYSICS_HEIGHT = PLAYER_HEIGHT; // Height of physics body (using sphere, so this isn't directly used like capsule)
|
| 20 |
+
const PLAYER_JUMP_FORCE = 8; // Adjust jump strength
|
| 21 |
const PROJECTILE_SPEED = 15;
|
| 22 |
const PROJECTILE_RADIUS = 0.2;
|
| 23 |
+
const PICKUP_RADIUS = 1.5; // How close player needs to be to pickup items
|
| 24 |
|
| 25 |
// --- Three.js Setup ---
|
| 26 |
let scene, camera, renderer;
|
| 27 |
let playerMesh;
|
| 28 |
const meshesToSync = [];
|
| 29 |
const projectiles = [];
|
| 30 |
+
let axesHelper;
|
| 31 |
|
| 32 |
// --- Physics Setup ---
|
| 33 |
let world;
|
| 34 |
let playerBody;
|
| 35 |
+
const physicsBodies = []; // Keep track of ALL bodies we add
|
| 36 |
+
let cannonDebugger = null;
|
| 37 |
|
| 38 |
// --- Game State ---
|
| 39 |
+
let gameState = {};
|
| 40 |
const keysPressed = {};
|
| 41 |
+
let gameLoopActive = false;
|
| 42 |
+
let animationFrameId = null; // To potentially cancel the loop
|
| 43 |
|
| 44 |
+
// --- Game Data (Simplified for Debugging, ensure 0,0 exists!) ---
|
| 45 |
const gameData = {
|
| 46 |
+
"0,0": { type: 'city', features: ['door_north', 'item_Key'], name: "City Square"},
|
| 47 |
+
"0,1": { type: 'forest', features: ['path_north', 'door_south', 'item_Healing_Potion'], name: "Forest Entrance" }, // Note item name change
|
| 48 |
+
"0,2": { type: 'forest', features: ['path_south', 'monster_goblin'], name: "Deep Forest"},
|
| 49 |
"1,1": { type: 'forest', features: ['river', 'path_west'], name: "River Bend" },
|
| 50 |
+
"-1,1": { type: 'ruins', features: ['path_east'], name: "Old Ruins"},
|
| 51 |
+
// Add more simple locations for testing movement
|
| 52 |
+
"1,0": { type: 'plains', features: ['door_west'], name: "East Plains"},
|
| 53 |
+
"-1,0": { type: 'plains', features: ['door_east'], name: "West Plains"},
|
| 54 |
+
|
| 55 |
};
|
| 56 |
|
| 57 |
const itemsData = {
|
|
|
|
| 65 |
// ...
|
| 66 |
};
|
| 67 |
|
| 68 |
+
// --- Materials and Geometries (Defined once) ---
|
| 69 |
+
const materials = {
|
| 70 |
+
floor_city: new THREE.MeshLambertMaterial({ color: 0xdeb887 }),
|
| 71 |
+
forest: new THREE.MeshLambertMaterial({ color: 0x228B22 }),
|
| 72 |
+
cave: new THREE.MeshLambertMaterial({ color: 0x696969 }),
|
| 73 |
+
ruins: new THREE.MeshLambertMaterial({ color: 0x778899 }),
|
| 74 |
+
plains: new THREE.MeshLambertMaterial({ color: 0x90EE90 }),
|
| 75 |
+
default_floor: new THREE.MeshLambertMaterial({ color: 0xaaaaaa }),
|
| 76 |
+
wall: new THREE.MeshLambertMaterial({ color: 0x888888 }), // Use Lambert for walls too (needs light)
|
| 77 |
+
// Basic materials for debug:
|
| 78 |
+
debug_player: new THREE.MeshBasicMaterial({ color: 0x0077ff, wireframe: true }),
|
| 79 |
+
debug_wall: new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
|
| 80 |
+
debug_item: new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true }),
|
| 81 |
+
debug_monster: new THREE.MeshBasicMaterial({ color: 0xff00ff, wireframe: true }),
|
| 82 |
+
};
|
| 83 |
+
const geometries = {
|
| 84 |
+
floor: new THREE.PlaneGeometry(ROOM_SIZE, ROOM_SIZE),
|
| 85 |
+
wallNS: new THREE.BoxGeometry(ROOM_SIZE, WALL_HEIGHT, WALL_THICKNESS),
|
| 86 |
+
wallEW: new THREE.BoxGeometry(WALL_THICKNESS, WALL_HEIGHT, ROOM_SIZE),
|
| 87 |
+
// Primitives for assembly
|
| 88 |
+
box: new THREE.BoxGeometry(1, 1, 1),
|
| 89 |
+
sphere: new THREE.SphereGeometry(0.5, 16, 16),
|
| 90 |
+
cylinder: new THREE.CylinderGeometry(0.5, 0.5, 1, 16),
|
| 91 |
+
cone: new THREE.ConeGeometry(0.5, 1, 16),
|
| 92 |
+
plane: new THREE.PlaneGeometry(1, 1),
|
| 93 |
+
};
|
| 94 |
+
|
| 95 |
+
|
| 96 |
// --- Initialization ---
|
| 97 |
|
| 98 |
function init() {
|
| 99 |
+
console.log("--- Initializing Game ---");
|
| 100 |
// Reset state cleanly
|
| 101 |
gameState = {
|
| 102 |
inventory: [],
|
| 103 |
stats: { hp: 30, maxHp: 30, strength: 7, wisdom: 5, courage: 6 },
|
| 104 |
+
position: { x: 0, z: 0 }, // Logical position, might not be needed now
|
| 105 |
+
monsters: [], // { id, type, hp, body, mesh }
|
| 106 |
+
items: [], // { id, name, body, mesh } - body might be null if not physics based
|
| 107 |
};
|
| 108 |
+
keysPressed = {};
|
| 109 |
meshesToSync.length = 0;
|
| 110 |
projectiles.length = 0;
|
| 111 |
physicsBodies.length = 0;
|
| 112 |
+
// Clear previous scene children if restarting
|
| 113 |
+
if (scene) {
|
| 114 |
+
while (scene.children.length > 0) {
|
| 115 |
+
scene.remove(scene.children[0]);
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
// Clear physics world bodies if restarting
|
| 119 |
+
if (world) {
|
| 120 |
+
while (world.bodies.length > 0) {
|
| 121 |
+
world.removeBody(world.bodies[0]);
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
|
| 125 |
|
| 126 |
initThreeJS();
|
| 127 |
initPhysics();
|
| 128 |
+
initPlayer(); // Player depends on physics world existing
|
| 129 |
+
generateMap(); // Map depends on physics world existing
|
| 130 |
setupInputListeners();
|
| 131 |
+
updateUI();
|
| 132 |
+
addLog("Welcome! Move: QWEASDZXC, Jump: Shift/X, Attack: Space, Pickup: F", "info");
|
| 133 |
+
|
| 134 |
+
console.log("--- Initialization Complete ---");
|
| 135 |
+
if (animationFrameId) cancelAnimationFrame(animationFrameId); // Stop previous loop if restarting
|
| 136 |
+
gameLoopActive = true;
|
| 137 |
+
animate();
|
| 138 |
}
|
| 139 |
|
| 140 |
function initThreeJS() {
|
| 141 |
console.log("Initializing Three.js...");
|
| 142 |
scene = new THREE.Scene();
|
| 143 |
+
scene.background = new THREE.Color(0x1a1a1a); // Match body background slightly better
|
| 144 |
|
| 145 |
+
const aspect = sceneContainer.clientWidth / sceneContainer.clientHeight;
|
| 146 |
+
camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 1000);
|
| 147 |
+
camera.position.set(0, CAMERA_Y_OFFSET, 5); // Start overhead, slightly back
|
| 148 |
+
camera.lookAt(0, 0, 0); // Look at origin initially
|
| 149 |
|
| 150 |
renderer = new THREE.WebGLRenderer({ antialias: true });
|
| 151 |
renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
|
| 152 |
renderer.shadowMap.enabled = true;
|
| 153 |
+
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Softer shadows
|
| 154 |
sceneContainer.appendChild(renderer.domElement);
|
| 155 |
|
| 156 |
// Lighting
|
| 157 |
+
scene.add(new THREE.AmbientLight(0xffffff, 0.6)); // More ambient light
|
| 158 |
+
const dirLight = new THREE.DirectionalLight(0xffffff, 1.0);
|
| 159 |
+
dirLight.position.set(20, 30, 15); // Adjust light direction
|
|
|
|
| 160 |
dirLight.castShadow = true;
|
| 161 |
+
dirLight.shadow.mapSize.width = 2048; // Increase shadow map resolution
|
| 162 |
+
dirLight.shadow.mapSize.height = 2048;
|
| 163 |
+
dirLight.shadow.camera.near = 1;
|
| 164 |
+
dirLight.shadow.camera.far = 60; // Adjust shadow camera range
|
| 165 |
+
const shadowCamSize = 25;
|
| 166 |
+
dirLight.shadow.camera.left = -shadowCamSize;
|
| 167 |
+
dirLight.shadow.camera.right = shadowCamSize;
|
| 168 |
+
dirLight.shadow.camera.top = shadowCamSize;
|
| 169 |
+
dirLight.shadow.camera.bottom = -shadowCamSize;
|
|
|
|
| 170 |
scene.add(dirLight);
|
| 171 |
+
// scene.add(new THREE.CameraHelper(dirLight.shadow.camera)); // Shadow debug
|
| 172 |
|
| 173 |
// Axes Helper
|
| 174 |
+
axesHelper = new THREE.AxesHelper(ROOM_SIZE * 0.5);
|
| 175 |
+
axesHelper.position.set(0, 0.01, 0); // Place it clearly
|
| 176 |
scene.add(axesHelper);
|
| 177 |
console.log("Three.js Initialized.");
|
| 178 |
|
|
|
|
| 181 |
|
| 182 |
function initPhysics() {
|
| 183 |
console.log("Initializing Cannon-es...");
|
| 184 |
+
world = new CANNON.World({ gravity: new CANNON.Vec3(0, -15, 0) }); // Slightly stronger gravity
|
| 185 |
+
world.broadphase = new CANNON.SAPBroadphase(world);
|
| 186 |
+
world.allowSleep = true;
|
| 187 |
+
|
| 188 |
+
// Define materials
|
| 189 |
+
const groundMaterial = new CANNON.Material("ground");
|
| 190 |
+
const playerMaterial = new CANNON.Material("player");
|
| 191 |
+
const wallMaterial = new CANNON.Material("wall");
|
| 192 |
+
const monsterMaterial = new CANNON.Material("monster");
|
| 193 |
+
const itemMaterial = new CANNON.Material("item"); // For trigger bodies if used
|
| 194 |
|
| 195 |
// Ground plane
|
| 196 |
const groundShape = new CANNON.Plane();
|
| 197 |
+
const groundBody = new CANNON.Body({ mass: 0, material: groundMaterial });
|
| 198 |
groundBody.addShape(groundShape);
|
| 199 |
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
|
| 200 |
world.addBody(groundBody);
|
| 201 |
+
physicsBodies.push(groundBody);
|
| 202 |
+
|
| 203 |
+
// Contact Materials (basic examples)
|
| 204 |
+
const playerGround = new CANNON.ContactMaterial(playerMaterial, groundMaterial, { friction: 0.3, restitution: 0.1 });
|
| 205 |
+
const playerWall = new CANNON.ContactMaterial(playerMaterial, wallMaterial, { friction: 0.0, restitution: 0.1 }); // Low friction vs walls
|
| 206 |
+
const monsterGround = new CANNON.ContactMaterial(monsterMaterial, groundMaterial, { friction: 0.4, restitution: 0.1 });
|
| 207 |
+
const monsterWall = new CANNON.ContactMaterial(monsterMaterial, wallMaterial, { friction: 0.1, restitution: 0.2 });
|
| 208 |
+
|
| 209 |
+
world.addContactMaterial(playerGround);
|
| 210 |
+
world.addContactMaterial(playerWall);
|
| 211 |
+
world.addContactMaterial(monsterGround);
|
| 212 |
+
world.addContactMaterial(monsterWall);
|
| 213 |
+
|
| 214 |
console.log("Physics World Initialized.");
|
| 215 |
|
| 216 |
+
// Optional: Physics Debugger Init
|
| 217 |
// try {
|
| 218 |
+
// cannonDebugger = new CannonDebugger(scene, world, { color: 0x00ff00, scale: 1.0 });
|
|
|
|
|
|
|
|
|
|
| 219 |
// console.log("Cannon-es Debugger Initialized.");
|
| 220 |
+
// } catch (e) { console.error("Failed to initialize CannonDebugger.", e); }
|
|
|
|
|
|
|
| 221 |
}
|
| 222 |
|
| 223 |
+
// --- Primitive Assembly Functions (Keep as before) ---
|
| 224 |
+
function createPlayerMesh() { /* ... same ... */
|
| 225 |
const group = new THREE.Group();
|
| 226 |
+
// Use DEBUG material temporarily
|
| 227 |
+
const bodyMat = materials.debug_player; //new THREE.MeshLambertMaterial({ color: 0x0077ff });
|
| 228 |
+
const bodyGeom = new THREE.CylinderGeometry(PLAYER_RADIUS, PLAYER_RADIUS, PLAYER_HEIGHT - (PLAYER_RADIUS * 2), 8); // Lower poly
|
| 229 |
const body = new THREE.Mesh(bodyGeom, bodyMat);
|
| 230 |
+
body.position.y = PLAYER_RADIUS; body.castShadow = true;
|
| 231 |
+
const headGeom = new THREE.SphereGeometry(PLAYER_RADIUS, 8, 8); // Lower poly
|
|
|
|
| 232 |
const head = new THREE.Mesh(headGeom, bodyMat);
|
| 233 |
+
head.position.y = PLAYER_HEIGHT - PLAYER_RADIUS; head.castShadow = true;
|
|
|
|
| 234 |
group.add(body); group.add(head);
|
| 235 |
+
const noseGeom = new THREE.ConeGeometry(PLAYER_RADIUS * 0.3, PLAYER_RADIUS * 0.5, 4); // Lower poly
|
| 236 |
const noseMat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
|
| 237 |
const nose = new THREE.Mesh(noseGeom, noseMat);
|
| 238 |
+
// Position nose correctly relative to player center (Y=PLAYER_HEIGHT/2)
|
| 239 |
+
nose.position.set(0, (PLAYER_HEIGHT / 2) * 0.9, -PLAYER_RADIUS); // Position Z forward, adjust Y
|
| 240 |
+
nose.rotation.x = Math.PI / 2 + Math.PI; // Point along -Z
|
| 241 |
group.add(nose);
|
| 242 |
+
group.position.y = PLAYER_HEIGHT / 2; // Set pivot to bottom center
|
| 243 |
return group;
|
| 244 |
+
}
|
| 245 |
+
function createSimpleMonsterMesh(modelType = 'capsule_green') { /* ... Mostly same, maybe use debug material ... */
|
| 246 |
const group = new THREE.Group();
|
| 247 |
+
let color = 0xff00ff; // Magenta debug default
|
| 248 |
+
let mat = materials.debug_monster; // Use debug material
|
| 249 |
if (modelType === 'capsule_green') {
|
| 250 |
color = 0x00ff00;
|
| 251 |
+
// mat = new THREE.MeshLambertMaterial({ color: color }); // Keep debug for now
|
| 252 |
+
const bodyGeom = new THREE.CylinderGeometry(0.4, 0.4, 1.0, 8); // Lower poly
|
| 253 |
+
const headGeom = new THREE.SphereGeometry(0.4, 8, 8);
|
| 254 |
const body = new THREE.Mesh(bodyGeom, mat);
|
| 255 |
const head = new THREE.Mesh(headGeom, mat);
|
| 256 |
body.position.y = 0.5; head.position.y = 1.0 + 0.4;
|
| 257 |
group.add(body); group.add(head);
|
| 258 |
+
} else { let geom = new THREE.BoxGeometry(0.8, 1.2, 0.8); const mesh = new THREE.Mesh(geom, mat); mesh.position.y = 0.6; group.add(mesh); }
|
| 259 |
group.traverse(child => { if (child.isMesh) child.castShadow = true; });
|
| 260 |
+
group.position.y = 1.2 / 2; // Center pivot
|
| 261 |
return group;
|
| 262 |
}
|
| 263 |
+
function createSimpleItemMesh(modelType = 'sphere_red') { /* ... Mostly same, maybe use debug material ... */
|
| 264 |
+
let geom, mat; let color = 0x00ff00; // Green debug default
|
| 265 |
+
mat = materials.debug_item; // Use debug material
|
| 266 |
+
if(modelType === 'sphere_red') { color = 0xff0000; geom = new THREE.SphereGeometry(0.3, 8, 8); }
|
| 267 |
else if (modelType === 'box_gold') { color = 0xffd700; geom = new THREE.BoxGeometry(0.4, 0.4, 0.4); }
|
| 268 |
+
else { geom = new THREE.SphereGeometry(0.3, 8, 8); }
|
| 269 |
+
// mat = new THREE.MeshStandardMaterial({ color: color, metalness: 0.3, roughness: 0.6 }); // Keep debug
|
| 270 |
+
const mesh = new THREE.Mesh(geom, mat);
|
| 271 |
+
mesh.position.y = PLAYER_RADIUS; // Place roughly at pickup height
|
| 272 |
+
mesh.castShadow = true;
|
| 273 |
return mesh;
|
| 274 |
}
|
| 275 |
+
function createProjectileMesh() { /* ... same ... */
|
| 276 |
+
const geom = new THREE.SphereGeometry(PROJECTILE_RADIUS, 6, 6); // Lower poly
|
| 277 |
const mat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
|
| 278 |
const mesh = new THREE.Mesh(geom, mat);
|
| 279 |
return mesh;
|
| 280 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
// --- Player Setup ---
|
| 282 |
function initPlayer() {
|
| 283 |
console.log("Initializing Player...");
|
| 284 |
// Visual Mesh
|
| 285 |
playerMesh = createPlayerMesh();
|
| 286 |
+
// Start position will be set by physics body sync
|
|
|
|
| 287 |
scene.add(playerMesh);
|
| 288 |
console.log("Player mesh added to scene.");
|
| 289 |
|
| 290 |
+
// Physics Body - Start at center of 0,0 cell, slightly above ground
|
| 291 |
+
const startX = 0 * ROOM_SIZE;
|
| 292 |
+
const startZ = 0 * ROOM_SIZE;
|
| 293 |
+
const startY = PLAYER_HEIGHT; // Start higher to ensure it settles onto ground
|
| 294 |
const playerShape = new CANNON.Sphere(PLAYER_RADIUS);
|
| 295 |
playerBody = new CANNON.Body({
|
| 296 |
+
mass: 70,
|
| 297 |
shape: playerShape,
|
| 298 |
+
position: new CANNON.Vec3(startX, startY, startZ),
|
| 299 |
+
linearDamping: 0.95,
|
| 300 |
+
angularDamping: 1.0,
|
| 301 |
+
material: world.materials.find(m => m.name === "player") || new CANNON.Material("player") // Get or create material
|
| 302 |
});
|
| 303 |
+
playerBody.allowSleep = false;
|
|
|
|
|
|
|
| 304 |
playerBody.addEventListener("collide", handlePlayerCollision);
|
| 305 |
world.addBody(playerBody);
|
| 306 |
+
physicsBodies.push(playerBody); // Track body
|
| 307 |
+
console.log(`Player physics body added at ${startX}, ${startY}, ${startZ}`);
|
| 308 |
|
| 309 |
// Add to sync list
|
| 310 |
meshesToSync.push({ mesh: playerMesh, body: playerBody });
|
| 311 |
+
console.log("Player added to sync list.");
|
| 312 |
}
|
| 313 |
|
| 314 |
// --- Map Generation ---
|
| 315 |
function generateMap() {
|
| 316 |
console.log("Generating Map...");
|
| 317 |
+
const wallPhysicsMaterial = world.materials.find(m => m.name === "wall") || new CANNON.Material("wall"); // Get or create material
|
| 318 |
+
const groundPhysicsMaterial = world.materials.find(m => m.name === "ground"); // Should exist from initPhysics
|
| 319 |
+
|
| 320 |
+
// Simplified: Only render a few cells around 0,0 for testing
|
| 321 |
+
const renderRadius = 1; // Render 0,0 and its immediate neighbours
|
| 322 |
+
for (let x = -renderRadius; x <= renderRadius; x++) {
|
| 323 |
+
for (let z = -renderRadius; z <= renderRadius; z++) {
|
| 324 |
+
const coordString = `${x},${z}`;
|
| 325 |
+
const data = gameData[coordString];
|
| 326 |
+
|
| 327 |
+
if (data) { // Only generate if data exists for this coord
|
| 328 |
+
console.log(`Generating cell: ${coordString}`);
|
| 329 |
+
const type = data.type || 'default';
|
| 330 |
+
|
| 331 |
+
// Create Floor Mesh
|
| 332 |
+
const floorMat = floorMaterials[type] || floorMaterials.default_floor;
|
| 333 |
+
const floorMesh = new THREE.Mesh(geometries.floor, floorMat);
|
| 334 |
+
floorMesh.rotation.x = -Math.PI / 2;
|
| 335 |
+
floorMesh.position.set(x * ROOM_SIZE, 0, z * ROOM_SIZE);
|
| 336 |
+
floorMesh.receiveShadow = true;
|
| 337 |
+
scene.add(floorMesh);
|
| 338 |
+
|
| 339 |
+
// Create Walls (Visual + Physics)
|
| 340 |
+
const features = data.features || [];
|
| 341 |
+
const wallDefs = [
|
| 342 |
+
['north', geometries.wallNS, 0, -0.5],
|
| 343 |
+
['south', geometries.wallNS, 0, 0.5],
|
| 344 |
+
['east', geometries.wallEW, 0.5, 0],
|
| 345 |
+
['west', geometries.wallEW, -0.5, 0],
|
| 346 |
+
];
|
| 347 |
+
|
| 348 |
+
wallDefs.forEach(([dir, geom, xOff, zOff]) => {
|
| 349 |
+
const doorFeature = `door_${dir}`;
|
| 350 |
+
const pathFeature = `path_${dir}`;
|
| 351 |
+
if (!features.includes(doorFeature) && !features.includes(pathFeature)) {
|
| 352 |
+
const wallX = x * ROOM_SIZE + xOff * ROOM_SIZE;
|
| 353 |
+
const wallZ = z * ROOM_SIZE + zOff * ROOM_SIZE;
|
| 354 |
+
const wallY = WALL_HEIGHT / 2;
|
| 355 |
+
|
| 356 |
+
// DEBUG Visual Wall
|
| 357 |
+
const wallMesh = new THREE.Mesh(geom, materials.debug_wall); // Use debug material
|
| 358 |
+
wallMesh.position.set(wallX, wallY, wallZ);
|
| 359 |
+
wallMesh.castShadow = true;
|
| 360 |
+
wallMesh.receiveShadow = true;
|
| 361 |
+
scene.add(wallMesh);
|
| 362 |
+
|
| 363 |
+
// Physics Wall
|
| 364 |
+
const wallShape = new CANNON.Box(new CANNON.Vec3(geom.parameters.width / 2, geom.parameters.height / 2, geom.parameters.depth / 2));
|
| 365 |
+
const wallBody = new CANNON.Body({ mass: 0, shape: wallShape, position: new CANNON.Vec3(wallX, wallY, wallZ), material: wallPhysicsMaterial });
|
| 366 |
+
world.addBody(wallBody);
|
| 367 |
+
physicsBodies.push(wallBody);
|
| 368 |
+
}
|
| 369 |
+
});
|
| 370 |
+
|
| 371 |
+
// Spawn Items & Monsters based on features
|
| 372 |
+
features.forEach(feature => {
|
| 373 |
+
if (feature.startsWith('item_')) {
|
| 374 |
+
const itemName = feature.substring(5).replace(/_/g, ' '); // Handle underscores
|
| 375 |
+
if (itemsData[itemName]) {
|
| 376 |
+
spawnItem(itemName, x, z);
|
| 377 |
+
} else { console.warn(`Item feature found but no data for: ${itemName}`); }
|
| 378 |
+
} else if (feature.startsWith('monster_')) {
|
| 379 |
+
const monsterType = feature.substring(8);
|
| 380 |
+
if (monstersData[monsterType]) {
|
| 381 |
+
spawnMonster(monsterType, x, z);
|
| 382 |
+
} else { console.warn(`Monster feature found but no data for: ${monsterType}`); }
|
| 383 |
+
}
|
| 384 |
+
// Handle other visual features if needed
|
| 385 |
+
});
|
| 386 |
+
|
| 387 |
+
} else {
|
| 388 |
+
console.log(`No data for cell: ${coordString}, skipping.`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
}
|
| 390 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
}
|
| 392 |
console.log("Map Generation Complete.");
|
| 393 |
}
|
| 394 |
|
| 395 |
+
function spawnItem(itemName, gridX, gridZ) {
|
| 396 |
const itemData = itemsData[itemName];
|
| 397 |
if (!itemData) return;
|
| 398 |
const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
|
| 399 |
const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
|
| 400 |
+
const y = PLAYER_RADIUS; // Item height
|
| 401 |
+
|
| 402 |
+
// Use DEBUG material
|
| 403 |
+
const mesh = new THREE.Mesh(geometries.sphere, materials.debug_item); // Simplified mesh
|
| 404 |
+
mesh.scale.set(0.6, 0.6, 0.6); // Make items smaller
|
| 405 |
mesh.position.set(x, y, z);
|
| 406 |
mesh.userData = { type: 'item', name: itemName };
|
| 407 |
+
mesh.castShadow = true;
|
| 408 |
scene.add(mesh);
|
| 409 |
+
|
| 410 |
+
// Store item in game state WITHOUT physics body initially for F pickup
|
| 411 |
+
gameState.items.push({
|
| 412 |
+
id: THREE.MathUtils.generateUUID(), // Simple unique ID
|
| 413 |
+
name: itemName,
|
| 414 |
+
mesh: mesh,
|
| 415 |
+
position: mesh.position // Store position for proximity check
|
| 416 |
+
});
|
| 417 |
+
console.log(`Spawned item ${itemName} at ${gridX},${gridZ} (visual only)`);
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
function spawnMonster(monsterType, gridX, gridZ) {
|
| 421 |
+
const monsterData = monstersData[monsterType];
|
| 422 |
+
if (!monsterData) return;
|
| 423 |
+
const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
|
| 424 |
+
const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
|
| 425 |
+
const y = PLAYER_HEIGHT; // Start higher
|
| 426 |
+
|
| 427 |
+
// Use DEBUG material
|
| 428 |
+
const mesh = createSimpleMonsterMesh(monsterData.model); // Assuming this uses debug mat now
|
| 429 |
+
mesh.position.set(x, y, z); // Set initial mesh pos
|
| 430 |
+
mesh.userData = { type: 'monster', monsterType: monsterType };
|
| 431 |
+
scene.add(mesh);
|
| 432 |
+
|
| 433 |
+
// Physics Body
|
| 434 |
+
const shape = new CANNON.Sphere(PLAYER_RADIUS * 0.8); // Simple sphere collider
|
| 435 |
+
const body = new CANNON.Body({
|
| 436 |
+
mass: 10,
|
| 437 |
+
shape: shape,
|
| 438 |
+
position: new CANNON.Vec3(x, y, z),
|
| 439 |
+
linearDamping: 0.8,
|
| 440 |
+
angularDamping: 0.9,
|
| 441 |
+
material: world.materials.find(m => m.name === "monster") || new CANNON.Material("monster")
|
| 442 |
+
});
|
| 443 |
+
body.allowSleep = true;
|
| 444 |
+
body.userData = { type: 'monster', monsterType: monsterType, mesh: mesh, hp: monsterData.hp };
|
| 445 |
world.addBody(body);
|
| 446 |
+
|
| 447 |
+
gameState.monsters.push({ id: body.id, type: monsterType, hp: monsterData.hp, body: body, mesh: mesh });
|
| 448 |
+
meshesToSync.push({ mesh: mesh, body: body });
|
| 449 |
physicsBodies.push(body);
|
| 450 |
+
console.log(`Spawned monster ${monsterType} at ${gridX},${gridZ}`);
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
// --- Input Handling (QWEASDZXC + Jump + F + Space) ---
|
| 455 |
+
function setupInputListeners() {
|
| 456 |
+
console.log("Setting up input listeners.");
|
| 457 |
+
window.addEventListener('keydown', (event) => {
|
| 458 |
+
keysPressed[event.key.toLowerCase()] = true;
|
| 459 |
+
keysPressed[event.code] = true; // Keep Space, Shift etc.
|
| 460 |
+
// Prevent default browser scroll on space/arrows
|
| 461 |
+
if (['space', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(event.code.toLowerCase())) {
|
| 462 |
+
event.preventDefault();
|
| 463 |
+
}
|
| 464 |
+
});
|
| 465 |
+
window.addEventListener('keyup', (event) => {
|
| 466 |
+
keysPressed[event.key.toLowerCase()] = false;
|
| 467 |
+
keysPressed[event.code] = false;
|
| 468 |
+
});
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
function handleInput(deltaTime) {
|
| 472 |
+
if (!playerBody) return;
|
| 473 |
+
|
| 474 |
+
const moveSpeed = PLAYER_SPEED;
|
| 475 |
+
const diagonalSpeed = moveSpeed / Math.sqrt(2); // Adjust speed for diagonal
|
| 476 |
+
|
| 477 |
+
let moveX = 0;
|
| 478 |
+
let moveZ = 0;
|
| 479 |
+
|
| 480 |
+
// Forward/Backward (W/S)
|
| 481 |
+
if (keysPressed['w']) moveZ -= 1;
|
| 482 |
+
if (keysPressed['s']) moveZ += 1;
|
| 483 |
+
|
| 484 |
+
// Strafe (A/D)
|
| 485 |
+
if (keysPressed['a']) moveX -= 1;
|
| 486 |
+
if (keysPressed['d']) moveX += 1;
|
| 487 |
+
|
| 488 |
+
// Diagonal Forward (Q/E)
|
| 489 |
+
if (keysPressed['q']) { moveZ -= 1; moveX -= 1; }
|
| 490 |
+
if (keysPressed['e']) { moveZ -= 1; moveX += 1; }
|
| 491 |
+
|
| 492 |
+
// Diagonal Backward (Z/C)
|
| 493 |
+
if (keysPressed['z']) { moveZ += 1; moveX -= 1; }
|
| 494 |
+
if (keysPressed['c']) { moveZ += 1; moveX += 1; }
|
| 495 |
+
|
| 496 |
+
// --- Calculate final velocity vector ---
|
| 497 |
+
const velocity = new CANNON.Vec3(0, playerBody.velocity.y, 0); // Preserve Y velocity for jump/gravity
|
| 498 |
+
|
| 499 |
+
// Normalize if moving
|
| 500 |
+
if (moveX !== 0 || moveZ !== 0) {
|
| 501 |
+
const moveVec = new THREE.Vector2(moveX, moveZ);
|
| 502 |
+
moveVec.normalize(); // Ensure consistent speed regardless of direction count
|
| 503 |
+
|
| 504 |
+
velocity.x = moveVec.x * moveSpeed;
|
| 505 |
+
velocity.z = moveVec.y * moveSpeed;
|
| 506 |
+
|
| 507 |
+
// Make player mesh face movement direction
|
| 508 |
+
// NOTE: This rotation assumes +Z is backward, -Z is forward
|
| 509 |
+
const angle = Math.atan2(velocity.x, velocity.z); // atan2(x, z) gives angle from positive Z axis
|
| 510 |
+
const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
|
| 511 |
+
// Smooth rotation (Slerp)
|
| 512 |
+
playerMesh.quaternion.slerp(targetQuaternion, 0.15); // Adjust 0.15 for faster/slower turning
|
| 513 |
+
|
| 514 |
+
} else {
|
| 515 |
+
// Apply damping implicitly via Cannon setting, or force stop:
|
| 516 |
+
velocity.x = 0;
|
| 517 |
+
velocity.z = 0;
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
playerBody.velocity.x = velocity.x;
|
| 521 |
+
playerBody.velocity.z = velocity.z;
|
| 522 |
+
// Y velocity is handled by gravity and jump impulse
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
// --- Jump (Shift or X) ---
|
| 526 |
+
// !! Basic jump - no ground check yet !!
|
| 527 |
+
if (keysPressed['shift'] || keysPressed['x']) {
|
| 528 |
+
// Simple check: only jump if Y velocity is near zero (crude ground check)
|
| 529 |
+
if (Math.abs(playerBody.velocity.y) < 0.1) {
|
| 530 |
+
console.log("Attempting Jump!");
|
| 531 |
+
playerBody.applyImpulse(new CANNON.Vec3(0, PLAYER_JUMP_FORCE, 0), playerBody.position);
|
| 532 |
+
}
|
| 533 |
+
keysPressed['shift'] = false; // Consume jump input
|
| 534 |
+
keysPressed['x'] = false;
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
// --- Pickup (F) ---
|
| 538 |
+
if (keysPressed['f']) {
|
| 539 |
+
pickupNearbyItem();
|
| 540 |
+
keysPressed['f'] = false; // Consume pickup input
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
// --- Fire (Space) ---
|
| 544 |
+
if (keysPressed['space']) {
|
| 545 |
+
fireProjectile();
|
| 546 |
+
keysPressed['space'] = false; // Consume fire input
|
| 547 |
+
}
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
// --- Interaction Logic ---
|
| 551 |
+
function pickupNearbyItem() {
|
| 552 |
+
if (!playerBody) return;
|
| 553 |
+
const playerPos = playerBody.position;
|
| 554 |
+
let pickedUp = false;
|
| 555 |
+
|
| 556 |
+
for (let i = gameState.items.length - 1; i >= 0; i--) {
|
| 557 |
+
const item = gameState.items[i];
|
| 558 |
+
const itemPos = item.position; // Using mesh position as items have no physics body now
|
| 559 |
+
const distance = playerPos.distanceTo(itemPos);
|
| 560 |
+
|
| 561 |
+
if (distance < PICKUP_RADIUS) {
|
| 562 |
+
if (!gameState.inventory.includes(item.name)) {
|
| 563 |
+
gameState.inventory.push(item.name);
|
| 564 |
+
addLog(`Picked up ${item.name}!`, "pickup");
|
| 565 |
+
updateInventoryDisplay();
|
| 566 |
+
|
| 567 |
+
// Remove item visually
|
| 568 |
+
scene.remove(item.mesh);
|
| 569 |
+
// Remove from game state list
|
| 570 |
+
gameState.items.splice(i, 1);
|
| 571 |
+
pickedUp = true;
|
| 572 |
+
break; // Pick up only one item per key press
|
| 573 |
+
}
|
| 574 |
+
}
|
| 575 |
+
}
|
| 576 |
+
if (!pickedUp) {
|
| 577 |
+
addLog("Nothing nearby to pick up.", "info");
|
| 578 |
+
}
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
// --- Combat (Keep Projectile Logic) ---
|
| 583 |
+
function fireProjectile() { /* ... same as before ... */
|
| 584 |
+
if (!playerBody || !playerMesh) return;
|
| 585 |
+
addLog("Pew!", "combat");
|
| 586 |
+
const projectileMesh = createProjectileMesh();
|
| 587 |
+
const projectileShape = new CANNON.Sphere(PROJECTILE_RADIUS);
|
| 588 |
+
const projectileBody = new CANNON.Body({ mass: 0.1, shape: projectileShape, linearDamping: 0.01, angularDamping: 0.01 });
|
| 589 |
+
projectileBody.addEventListener("collide", handleProjectileCollision);
|
| 590 |
+
const offsetDistance = PLAYER_RADIUS + PROJECTILE_RADIUS + 0.1;
|
| 591 |
+
const direction = new THREE.Vector3(0, 0, -1); // Base direction -Z is forward
|
| 592 |
+
direction.applyQuaternion(playerMesh.quaternion);
|
| 593 |
+
const startPos = new CANNON.Vec3().copy(playerBody.position).vadd(
|
| 594 |
+
new CANNON.Vec3(direction.x, 0, direction.z).scale(offsetDistance)
|
| 595 |
+
);
|
| 596 |
+
startPos.y = playerBody.position.y + PLAYER_HEIGHT * 0.3; // Fire from mid-height approx
|
| 597 |
+
projectileBody.position.copy(startPos);
|
| 598 |
+
projectileMesh.position.copy(startPos);
|
| 599 |
+
projectileBody.velocity = new CANNON.Vec3(direction.x, 0, direction.z).scale(PROJECTILE_SPEED);
|
| 600 |
+
scene.add(projectileMesh);
|
| 601 |
+
world.addBody(projectileBody);
|
| 602 |
+
const projectileData = { mesh: projectileMesh, body: projectileBody, lifetime: 3.0 };
|
| 603 |
+
meshesToSync.push(projectileData);
|
| 604 |
+
projectiles.push(projectileData);
|
| 605 |
+
physicsBodies.push(projectileBody);
|
| 606 |
+
projectileBody.userData = { type: 'projectile', mesh: projectileMesh, data: projectileData };
|
| 607 |
+
projectileMesh.userData = { type: 'projectile', body: projectileBody, data: projectileData };
|
| 608 |
+
}
|
| 609 |
+
|
| 610 |
+
// --- Collision Handling ---
|
| 611 |
+
function handlePlayerCollision(event) { /* ... same as before (but item part is unused now) ... */
|
| 612 |
+
const otherBody = event.body;
|
| 613 |
+
if (!otherBody || !otherBody.userData) return; // Body might be removed already
|
| 614 |
+
|
| 615 |
+
// Item pickup handled by 'F' key now.
|
| 616 |
+
|
| 617 |
+
// Player <-> Monster Collision
|
| 618 |
+
if (otherBody.userData.type === 'monster') {
|
| 619 |
+
// Cooldown for taking damage? Needs state tracking.
|
| 620 |
+
// Simple damage for now:
|
| 621 |
+
gameState.stats.hp -= 1;
|
| 622 |
+
addLog(`Hit by ${otherBody.userData.monsterType || 'monster'}! HP: ${gameState.stats.hp}`, "combat");
|
| 623 |
+
updateStatsDisplay();
|
| 624 |
+
if (gameState.stats.hp <= 0) { gameOver("Defeated by a monster!"); }
|
| 625 |
+
}
|
| 626 |
+
// Could add other collision handlers (player hitting wall hard, etc.)
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
function handleProjectileCollision(event) { /* ... same as before ... */
|
| 630 |
+
const projectileBody = event.target;
|
| 631 |
+
const otherBody = event.body;
|
| 632 |
+
if (!projectileBody || !projectileBody.userData || !otherBody || !otherBody.userData) return;
|
| 633 |
+
|
| 634 |
+
const projectileData = projectileBody.userData.data;
|
| 635 |
+
|
| 636 |
+
if (otherBody.userData.type === 'monster') {
|
| 637 |
+
const monsterId = otherBody.id;
|
| 638 |
+
const monsterIndex = gameState.monsters.findIndex(m => m.id === monsterId);
|
| 639 |
+
if (monsterIndex > -1) {
|
| 640 |
+
const monster = gameState.monsters[monsterIndex];
|
| 641 |
+
const damage = gameState.stats.strength;
|
| 642 |
+
monster.hp -= damage;
|
| 643 |
+
otherBody.userData.hp = monster.hp; // Update hp in body too
|
| 644 |
+
addLog(`Hit ${otherBody.userData.monsterType} for ${damage} damage! (HP: ${monster.hp})`, "combat");
|
| 645 |
+
if (monster.hp <= 0) {
|
| 646 |
+
addLog(`Defeated ${otherBody.userData.monsterType}!`, "info");
|
| 647 |
+
// Schedule removal after physics step if needed, direct removal can be tricky
|
| 648 |
+
scene.remove(monster.mesh);
|
| 649 |
+
world.removeBody(monster.body);
|
| 650 |
+
meshesToSync = meshesToSync.filter(sync => sync.body.id !== monster.body.id);
|
| 651 |
+
physicsBodies = physicsBodies.filter(body => body.id !== monster.body.id);
|
| 652 |
+
gameState.monsters.splice(monsterIndex, 1);
|
| 653 |
+
}
|
| 654 |
+
}
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
// Remove projectile immediately after any valid collision (except maybe player?)
|
| 658 |
+
if (otherBody !== playerBody) {
|
| 659 |
+
// Schedule removal might be safer if errors occur here
|
| 660 |
+
removeProjectile(projectileData);
|
| 661 |
+
}
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
function removeProjectile(projectileData) { /* ... same as before ... */
|
| 665 |
+
if (!projectileData) return;
|
| 666 |
+
const index = projectiles.indexOf(projectileData);
|
| 667 |
+
if (index === -1) return; // Already removed
|
| 668 |
+
|
| 669 |
+
// Check if objects still exist before removing
|
| 670 |
+
if(projectileData.mesh.parent) scene.remove(projectileData.mesh);
|
| 671 |
+
// Check if body is still in world before removing
|
| 672 |
+
if (world.bodies.includes(projectileData.body)) world.removeBody(projectileData.body);
|
| 673 |
+
|
| 674 |
+
meshesToSync = meshesToSync.filter(sync => sync.body && sync.body.id !== projectileData.body.id);
|
| 675 |
+
physicsBodies = physicsBodies.filter(body => body && body.id !== projectileData.body.id);
|
| 676 |
+
projectiles.splice(index, 1);
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
// --- Monster AI ---
|
| 680 |
+
function updateMonsters(deltaTime) { /* ... Mostly same as before ... */
|
| 681 |
+
const agroRangeSq = (ROOM_SIZE * 1.5) ** 2;
|
| 682 |
+
if(!playerBody) return; // Need player position
|
| 683 |
+
|
| 684 |
+
gameState.monsters.forEach(monster => {
|
| 685 |
+
if (!monster || !monster.body) return; // Skip if monster removed
|
| 686 |
+
const monsterPos = monster.body.position;
|
| 687 |
+
const playerPos = playerBody.position;
|
| 688 |
+
const distanceSq = playerPos.distanceSquared(monsterPos);
|
| 689 |
+
|
| 690 |
+
if (distanceSq < agroRangeSq) {
|
| 691 |
+
const direction = playerPos.vsub(monsterPos);
|
| 692 |
+
direction.y = 0;
|
| 693 |
+
if (direction.lengthSquared() > 0.1) {
|
| 694 |
+
direction.normalize();
|
| 695 |
+
const monsterData = monstersData[monster.type];
|
| 696 |
+
const speed = monsterData ? monsterData.speed : 1;
|
| 697 |
+
// Apply force instead of setting velocity for more 'physical' movement
|
| 698 |
+
// monster.body.applyForce(direction.scale(speed * monster.body.mass * 0.5), monsterPos); // Adjust force multiplier
|
| 699 |
+
// OR setting velocity is simpler for basic chase:
|
| 700 |
+
monster.body.velocity.x = direction.x * speed;
|
| 701 |
+
monster.body.velocity.z = direction.z * speed;
|
| 702 |
+
|
| 703 |
+
// Rotation
|
| 704 |
+
const angle = Math.atan2(direction.x, direction.z);
|
| 705 |
+
const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
|
| 706 |
+
monster.mesh.quaternion.slerp(targetQuaternion, 0.1); // Smooth turn
|
| 707 |
+
} else { monster.body.velocity.x = 0; monster.body.velocity.z = 0;} // Stop if close
|
| 708 |
+
} else { // Stop if far
|
| 709 |
+
monster.body.velocity.x = 0;
|
| 710 |
+
monster.body.velocity.z = 0;
|
| 711 |
+
}
|
| 712 |
+
});
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
// --- UI Update ---
|
| 717 |
+
function updateUI() { /* ... same as before ... */
|
| 718 |
+
updateStatsDisplay();
|
| 719 |
+
updateInventoryDisplay();
|
| 720 |
+
}
|
| 721 |
+
function updateStatsDisplay() { /* ... same as before ... */
|
| 722 |
+
let statsHTML = '';
|
| 723 |
+
statsHTML += `<span>HP: ${gameState.stats.hp}/${gameState.stats.maxHp}</span>`;
|
| 724 |
+
statsHTML += `<span>Str: ${gameState.stats.strength}</span>`;
|
| 725 |
+
statsHTML += `<span>Wis: ${gameState.stats.wisdom}</span>`;
|
| 726 |
+
statsHTML += `<span>Cor: ${gameState.stats.courage}</span>`;
|
| 727 |
+
statsElement.innerHTML = statsHTML;
|
| 728 |
+
}
|
| 729 |
+
function updateInventoryDisplay() { /* ... same as before ... */
|
| 730 |
+
let inventoryHTML = '';
|
| 731 |
+
if (gameState.inventory.length === 0) { inventoryHTML += '<em>Empty</em>'; }
|
| 732 |
+
else { gameState.inventory.forEach(item => { const itemInfo = itemsData[item] || { type: 'unknown', description: '???' }; const itemClass = `item-${itemInfo.type || 'unknown'}`; inventoryHTML += `<span class="${itemClass}" title="${itemInfo.description}">${item}</span>`; }); }
|
| 733 |
+
inventoryElement.innerHTML = inventoryHTML;
|
| 734 |
+
}
|
| 735 |
+
function addLog(message, type = "info") { /* ... same as before ... */
|
| 736 |
+
const p = document.createElement('p');
|
| 737 |
+
p.classList.add(type);
|
| 738 |
+
p.textContent = `[${new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}] ${message}`; // Add timestamp
|
| 739 |
+
logElement.appendChild(p);
|
| 740 |
+
logElement.scrollTop = logElement.scrollHeight;
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
// --- Game Over ---
|
| 745 |
+
function gameOver(reason) {
|
| 746 |
+
addLog(`GAME OVER: ${reason}`, "error");
|
| 747 |
+
console.log("Game Over:", reason);
|
| 748 |
+
gameLoopActive = false; // Stop the game loop
|
| 749 |
+
// Optional: Show a restart button or overlay
|
| 750 |
+
const restartButton = document.createElement('button');
|
| 751 |
+
restartButton.textContent = "RESTART GAME";
|
| 752 |
+
restartButton.style.position = 'absolute';
|
| 753 |
+
restartButton.style.top = '50%';
|
| 754 |
+
restartButton.style.left = '50%';
|
| 755 |
+
restartButton.style.transform = 'translate(-50%, -50%)';
|
| 756 |
+
restartButton.style.padding = '20px 40px';
|
| 757 |
+
restartButton.style.fontSize = '2em';
|
| 758 |
+
restartButton.style.cursor = 'pointer';
|
| 759 |
+
restartButton.style.zIndex = '1000';
|
| 760 |
+
restartButton.onclick = () => {
|
| 761 |
+
// Clean up restart button if exists
|
| 762 |
+
const oldButton = document.getElementById('restart-button');
|
| 763 |
+
if (oldButton) oldButton.remove();
|
| 764 |
+
init(); // Re-initialize the game
|
| 765 |
+
};
|
| 766 |
+
restartButton.id = 'restart-button'; // Assign ID for potential removal
|
| 767 |
+
sceneContainer.appendChild(restartButton); // Add button over the scene
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
// --- Main Game Loop ---
|
| 772 |
+
let lastTime = 0;
|
| 773 |
+
function animate(time) {
|
| 774 |
+
if (!gameLoopActive) return; // Stop loop if game over or paused
|
| 775 |
+
|
| 776 |
+
animationFrameId = requestAnimationFrame(animate); // Store ID to potentially cancel
|
| 777 |
+
|
| 778 |
+
const currentTime = performance.now(); // Use performance.now for higher precision
|
| 779 |
+
const deltaTime = (currentTime - lastTime) * 0.001; // Seconds
|
| 780 |
+
lastTime = currentTime;
|
| 781 |
+
|
| 782 |
+
// Avoid spiral of death on tab-out or large lag spikes
|
| 783 |
+
const dtClamped = Math.min(deltaTime, 1 / 30); // Clamp to max 30 FPS step
|
| 784 |
+
|
| 785 |
+
if (!world || !playerBody) return; // Exit if physics/player not ready
|
| 786 |
+
|
| 787 |
+
// 1. Handle Input
|
| 788 |
+
handleInput(dtClamped);
|
| 789 |
+
|
| 790 |
+
// 2. Update AI
|
| 791 |
+
updateMonsters(dtClamped);
|
| 792 |
+
|
| 793 |
+
// 3. Step Physics World
|
| 794 |
+
try {
|
| 795 |
+
world.step(dtClamped); // Use clamped delta time
|
| 796 |
+
} catch (e) {
|
| 797 |
+
console.error("Physics step error:", e);
|
| 798 |
+
// Potentially pause or handle error state
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
// 4. Update Projectiles
|
| 803 |
+
for (let i = projectiles.length - 1; i >= 0; i--) {
|
| 804 |
+
const p = projectiles[i];
|
| 805 |
+
if (p) { // Check if projectile still exists
|
| 806 |
+
p.lifetime -= dtClamped;
|
| 807 |
+
if (p.lifetime <= 0) {
|
| 808 |
+
removeProjectile(p);
|
| 809 |
+
}
|
| 810 |
+
}
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
// 5. Sync Visuals with Physics
|
| 814 |
+
meshesToSync.forEach(item => {
|
| 815 |
+
// Ensure body and mesh still exist before syncing
|
| 816 |
+
if (item && item.body && item.mesh && item.mesh.parent) {
|
| 817 |
+
item.mesh.position.copy(item.body.position);
|
| 818 |
+
item.mesh.quaternion.copy(item.body.quaternion);
|
| 819 |
+
} else {
|
| 820 |
+
// Clean up entries for objects that might have been removed improperly
|
| 821 |
+
console.warn("Attempted to sync missing body/mesh pair.");
|
| 822 |
+
// Maybe remove this entry from meshesToSync here? Needs careful handling.
|
| 823 |
+
}
|
| 824 |
+
});
|
| 825 |
+
|
| 826 |
+
// 6. Update Camera
|
| 827 |
+
if (playerBody) {
|
| 828 |
+
const targetCameraPos = new THREE.Vector3(
|
| 829 |
+
playerBody.position.x,
|
| 830 |
+
CAMERA_Y_OFFSET,
|
| 831 |
+
playerBody.position.z + CAMERA_Y_OFFSET * 0.5 // Adjust Z offset based on height for better angle
|
| 832 |
+
);
|
| 833 |
+
camera.position.lerp(targetCameraPos, 0.08); // Smoother follow
|
| 834 |
+
|
| 835 |
+
const lookAtPos = new THREE.Vector3(playerBody.position.x, 0, playerBody.position.z);
|
| 836 |
+
camera.lookAt(lookAtPos);
|
| 837 |
+
}
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
// 7. Physics Debugger Update (Optional)
|
| 841 |
+
// if (cannonDebugger) {
|
| 842 |
+
// cannonDebugger.update();
|
| 843 |
+
// }
|
| 844 |
+
|
| 845 |
+
// 8. Render Scene
|
| 846 |
+
renderer.render(scene, camera);
|
| 847 |
+
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
// --- Start Game ---
|
| 851 |
+
init();
|