awacke1 commited on
Commit
38289dd
·
verified ·
1 Parent(s): 06d7ab8

Update game.js

Browse files
Files changed (1) hide show
  1. game.js +448 -481
game.js CHANGED
@@ -1,6 +1,6 @@
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');
@@ -10,86 +10,96 @@ const logElement = document.getElementById('log-display');
10
 
11
  // --- Config ---
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 = {
58
- "Healing Potion": { type: "consumable", description: "Restores 10 HP.", hpRestore: 10, model: 'sphere_red' },
59
- "Key": { type: "quest", description: "A rusty key.", model: 'box_gold'},
60
- // ...
61
  };
62
 
63
- const monstersData = {
64
- "goblin": { hp: 15, attack: 4, defense: 1, speed: 2, model: 'capsule_green', xp: 5 },
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
 
@@ -97,112 +107,100 @@ const geometries = {
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
 
179
  window.addEventListener('resize', onWindowResize, false);
180
  }
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
 
@@ -210,100 +208,87 @@ function initPhysics() {
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
@@ -314,84 +299,79 @@ function initPlayer() {
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;
@@ -400,21 +380,21 @@ function spawnItem(itemName, gridX, gridZ) {
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) {
@@ -425,119 +405,110 @@ function spawnMonster(monsterType, gridX, gridZ) {
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) ---
@@ -552,299 +523,295 @@ 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 ---
 
1
  import * as THREE from 'three';
2
  import * as CANNON from 'cannon-es';
3
+ // import CannonDebugger from 'cannon-es-debugger'; // Keep commented for now
4
 
5
  // --- DOM Elements ---
6
  const sceneContainer = document.getElementById('scene-container');
 
10
 
11
  // --- Config ---
12
  const ROOM_SIZE = 10;
13
+ const WALL_HEIGHT = 3; // Slightly shorter walls
14
  const WALL_THICKNESS = 0.5;
15
+ const CAMERA_Y_OFFSET = 25; // Higher camera
16
+ const PLAYER_SPEED = 6;
17
  const PLAYER_RADIUS = 0.5;
18
  const PLAYER_HEIGHT = 1.8; // Visual height
19
+ const PLAYER_JUMP_IMPULSE = 7; // Impulse force for jump
 
20
  const PROJECTILE_SPEED = 15;
21
  const PROJECTILE_RADIUS = 0.2;
22
+ const PICKUP_RADIUS = 1.5;
23
+ const PICKUP_RADIUS_SQ = PICKUP_RADIUS * PICKUP_RADIUS; // Use squared distance
24
 
25
  // --- Three.js Setup ---
26
  let scene, camera, renderer;
27
  let playerMesh;
28
+ const meshesToSync = []; // Holds { mesh: THREE.Mesh, body: CANNON.Body }
29
+ const projectiles = []; // Holds { mesh, body, lifetime }
30
  let axesHelper;
31
 
32
  // --- Physics Setup ---
33
  let world;
34
  let playerBody;
35
+ const physicsBodies = new Map(); // Use Map<id, CANNON.Body> for easier removal
36
+ let groundMaterial, playerMaterial, wallMaterial, monsterMaterial, itemMaterial; // Physics materials
37
  let cannonDebugger = null;
38
 
39
  // --- Game State ---
40
  let gameState = {};
41
  const keysPressed = {};
42
  let gameLoopActive = false;
43
+ let animationFrameId = null;
44
+ let selectedTool = null; // For building tools later
45
 
46
+ // --- Game Data (Ensure starting point 0,0 exists!) ---
47
  const gameData = {
48
+ // Structure: "x,y": { type, features?, items?, monsters?, name? }
49
  "0,0": { type: 'city', features: ['door_north', 'item_Key'], name: "City Square"},
50
+ "0,1": { type: 'forest', features: ['path_north', 'door_south', 'item_Healing_Potion'], name: "Forest Entrance" },
51
  "0,2": { type: 'forest', features: ['path_south', 'monster_goblin'], name: "Deep Forest"},
52
  "1,1": { type: 'forest', features: ['river', 'path_west'], name: "River Bend" },
53
  "-1,1": { type: 'ruins', features: ['path_east'], name: "Old Ruins"},
 
54
  "1,0": { type: 'plains', features: ['door_west'], name: "East Plains"},
55
  "-1,0": { type: 'plains', features: ['door_east'], name: "West Plains"},
 
56
  };
57
 
58
+ const itemsData = { // Add 'name' for consistency
59
+ "Healing Potion": { name: "Healing Potion", type: "consumable", description: "Restores 10 HP.", hpRestore: 10, model: 'sphere_red' },
60
+ "Key": { name: "Key", type: "quest", description: "A rusty key.", model: 'box_gold'},
 
61
  };
62
 
63
+ const monstersData = { // Add 'name'
64
+ "goblin": { name: "Goblin", hp: 15, attack: 4, defense: 1, speed: 2.5, model: 'capsule_green', xp: 5 },
 
65
  };
66
 
67
  // --- Materials and Geometries (Defined once) ---
68
+ // Using basic wireframe materials for initial debugging
69
+ const debugMaterials = {
70
+ player: new THREE.MeshBasicMaterial({ color: 0x0077ff, wireframe: true }),
71
+ wall: new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
72
+ item: new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true }),
73
+ monster: new THREE.MeshBasicMaterial({ color: 0xff00ff, wireframe: true }),
74
+ projectile: new THREE.MeshBasicMaterial({ color: 0xffff00 }), // Keep projectiles solid
75
+ floor_default: new THREE.MeshBasicMaterial({ color: 0x555555, wireframe: true }), // Wireframe floor
 
 
 
 
 
76
  };
77
+ // Normal Materials (Use after debugging)
78
+ // const normalMaterials = {
79
+ // player: new THREE.MeshLambertMaterial({ color: 0x0077ff }),
80
+ // wall: new THREE.MeshLambertMaterial({ color: 0x888888 }),
81
+ // item_consumable: new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.6 }),
82
+ // item_quest: new THREE.MeshStandardMaterial({ color: 0xffd700, roughness: 0.4 }),
83
+ // monster_goblin: new THREE.MeshLambertMaterial({ color: 0x00ff00 }),
84
+ // floor_city: new THREE.MeshLambertMaterial({ color: 0xdeb887 }),
85
+ // floor_forest: new THREE.MeshLambertMaterial({ color: 0x228B22 }),
86
+ // // ... add all floor types
87
+ // floor_default: new THREE.MeshLambertMaterial({ color: 0xaaaaaa })
88
+ // };
89
+ const activeMaterials = debugMaterials; // Switch to normalMaterials when ready
90
+
91
+ const geometries = { // Keep geometries simple
92
  floor: new THREE.PlaneGeometry(ROOM_SIZE, ROOM_SIZE),
93
  wallNS: new THREE.BoxGeometry(ROOM_SIZE, WALL_HEIGHT, WALL_THICKNESS),
94
  wallEW: new THREE.BoxGeometry(WALL_THICKNESS, WALL_HEIGHT, ROOM_SIZE),
95
+ playerCylinder: new THREE.CylinderGeometry(PLAYER_RADIUS, PLAYER_RADIUS, PLAYER_HEIGHT - (PLAYER_RADIUS * 2), 8),
96
+ playerSphere: new THREE.SphereGeometry(PLAYER_RADIUS, 8, 8),
97
+ playerNose: new THREE.ConeGeometry(PLAYER_RADIUS * 0.3, PLAYER_RADIUS * 0.5, 4),
98
+ monsterCapsuleBody: new THREE.CylinderGeometry(0.4, 0.4, 1.0, 8),
99
+ monsterCapsuleHead: new THREE.SphereGeometry(0.4, 8, 8),
100
+ itemSphere: new THREE.SphereGeometry(0.3, 8, 8),
101
+ itemBox: new THREE.BoxGeometry(0.4, 0.4, 0.4),
102
+ projectile: new THREE.SphereGeometry(PROJECTILE_RADIUS, 6, 6),
103
  };
104
 
105
 
 
107
 
108
  function init() {
109
  console.log("--- Initializing Game ---");
110
+ // Reset state and clear arrays/maps
111
+ gameState = { inventory: [], stats: { hp: 30, maxHp: 30, strength: 7, wisdom: 5, courage: 6 }, monsters: [], items: [] };
 
 
 
 
 
 
112
  keysPressed = {};
113
  meshesToSync.length = 0;
114
  projectiles.length = 0;
115
+ physicsBodies.clear(); // Clear the map
116
+
117
+ // Clear previous scene if restarting
118
  if (scene) {
119
+ while (scene.children.length > 0) scene.remove(scene.children[0]);
120
+ } else {
121
+ scene = new THREE.Scene(); // Create scene only if it doesn't exist
122
  }
123
+ scene.background = new THREE.Color(0x1a1a1a);
 
 
 
 
 
124
 
125
+ // Clear previous renderer if restarting
126
+ if (renderer) {
127
+ renderer.dispose();
128
+ if (renderer.domElement.parentNode) {
129
+ renderer.domElement.parentNode.removeChild(renderer.domElement);
130
+ }
131
+ }
132
 
133
+ initThreeJS(); // Setup camera, renderer, lights
134
+ initPhysics(); // Setup world, materials
135
+ initPlayer(); // Setup player mesh + body
136
+ generateMap(); // Setup static map meshes + bodies
137
  setupInputListeners();
138
  updateUI();
139
+ addLog("Welcome! Move: QWEASDZXC, Jump: X, Attack: Space, Pickup: F", "info");
 
140
  console.log("--- Initialization Complete ---");
141
+
142
+ if (animationFrameId) cancelAnimationFrame(animationFrameId);
143
  gameLoopActive = true;
144
  animate();
145
  }
146
 
147
  function initThreeJS() {
148
  console.log("Initializing Three.js...");
 
 
 
149
  const aspect = sceneContainer.clientWidth / sceneContainer.clientHeight;
150
  camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 1000);
151
+ // Set camera directly overhead looking down
152
+ camera.position.set(0, CAMERA_Y_OFFSET, 0);
153
+ camera.lookAt(0, 0, 0); // Look straight down at origin initially
154
+ camera.rotation.x = -Math.PI / 2; // Explicitly set rotation if lookAt isn't enough
155
 
156
  renderer = new THREE.WebGLRenderer({ antialias: true });
157
  renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
158
  renderer.shadowMap.enabled = true;
159
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
160
  sceneContainer.appendChild(renderer.domElement);
161
 
162
  // Lighting
163
+ scene.add(new THREE.AmbientLight(0xffffff, 0.7)); // Brighter ambient for debug
164
  const dirLight = new THREE.DirectionalLight(0xffffff, 1.0);
165
+ dirLight.position.set(10, 30, 20); // Angled light
166
  dirLight.castShadow = true;
167
+ dirLight.shadow.mapSize.width = 1024;
168
+ dirLight.shadow.mapSize.height = 1024;
 
 
 
 
 
 
 
169
  scene.add(dirLight);
 
170
 
171
  // Axes Helper
172
  axesHelper = new THREE.AxesHelper(ROOM_SIZE * 0.5);
173
+ axesHelper.position.set(0, 0.01, 0);
174
  scene.add(axesHelper);
175
+ console.log("Three.js Initialized. Camera at:", camera.position);
176
 
177
  window.addEventListener('resize', onWindowResize, false);
178
  }
179
 
180
  function initPhysics() {
181
  console.log("Initializing Cannon-es...");
182
+ world = new CANNON.World({ gravity: new CANNON.Vec3(0, -15, 0) });
183
  world.broadphase = new CANNON.SAPBroadphase(world);
184
  world.allowSleep = true;
185
 
186
  // Define materials
187
+ groundMaterial = new CANNON.Material("ground");
188
+ playerMaterial = new CANNON.Material("player");
189
+ wallMaterial = new CANNON.Material("wall");
190
+ monsterMaterial = new CANNON.Material("monster");
191
+ itemMaterial = new CANNON.Material("item"); // Not used for physics bodies anymore
192
 
193
+ // Ground physics body
194
  const groundShape = new CANNON.Plane();
195
  const groundBody = new CANNON.Body({ mass: 0, material: groundMaterial });
196
  groundBody.addShape(groundShape);
197
  groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
198
  world.addBody(groundBody);
199
+ physicsBodies.set(groundBody.id, groundBody); // Track it
200
 
201
+ // Contact Materials
202
+ const playerGround = new CANNON.ContactMaterial(playerMaterial, groundMaterial, { friction: 0.1, restitution: 0.1 }); // Low friction
203
+ const playerWall = new CANNON.ContactMaterial(playerMaterial, wallMaterial, { friction: 0.01, restitution: 0.1 }); // Very low friction vs walls
204
  const monsterGround = new CANNON.ContactMaterial(monsterMaterial, groundMaterial, { friction: 0.4, restitution: 0.1 });
205
  const monsterWall = new CANNON.ContactMaterial(monsterMaterial, wallMaterial, { friction: 0.1, restitution: 0.2 });
206
 
 
208
  world.addContactMaterial(playerWall);
209
  world.addContactMaterial(monsterGround);
210
  world.addContactMaterial(monsterWall);
 
211
  console.log("Physics World Initialized.");
212
 
213
  // Optional: Physics Debugger Init
214
+ // try { cannonDebugger = new CannonDebugger(scene, world, { color: 0x00ff00 }); console.log("Debugger Init."); }
215
+ // catch (e) { console.error("Failed CannonDebugger.", e); }
 
 
216
  }
217
 
218
+ // --- Primitive Assembly Functions ---
219
+ function createPlayerMesh() {
220
  const group = new THREE.Group();
221
+ const bodyMat = activeMaterials.player; // Use active material set
222
+ const body = new THREE.Mesh(geometries.playerCylinder, bodyMat);
 
 
223
  body.position.y = PLAYER_RADIUS; body.castShadow = true;
224
+ const head = new THREE.Mesh(geometries.playerSphere, bodyMat);
 
225
  head.position.y = PLAYER_HEIGHT - PLAYER_RADIUS; head.castShadow = true;
226
  group.add(body); group.add(head);
227
+ const nose = new THREE.Mesh(geometries.playerNose, new THREE.MeshBasicMaterial({ color: 0xffff00 })); // Nose always bright yellow
228
+ nose.position.set(0, PLAYER_HEIGHT * 0.6, PLAYER_RADIUS); // Point forward +Z
229
+ // No rotation needed if pointing +Z
 
 
 
230
  group.add(nose);
231
+ // Important: Set group's origin to the intended base/center of the physics body
232
+ group.position.set(0, 0, 0); // Position will be controlled by sync
233
  return group;
234
+ }
235
+ function createSimpleMonsterMesh(modelType = 'capsule_green') {
236
  const group = new THREE.Group();
237
+ const mat = activeMaterials.monster; // Use active debug/normal material
 
238
  if (modelType === 'capsule_green') {
239
+ const body = new THREE.Mesh(geometries.monsterCapsuleBody, mat);
240
+ const head = new THREE.Mesh(geometries.monsterCapsuleHead, mat);
 
 
 
 
241
  body.position.y = 0.5; head.position.y = 1.0 + 0.4;
242
  group.add(body); group.add(head);
243
+ } else { /* Add other monster types if needed */ }
244
  group.traverse(child => { if (child.isMesh) child.castShadow = true; });
245
+ group.position.set(0, 0, 0); // Position set by sync
246
  return group;
247
  }
248
+ function createSimpleItemMesh(modelType = 'sphere_red') {
249
+ let geom;
250
+ const mat = activeMaterials.item; // Use active debug/normal material
251
+ if(modelType === 'sphere_red') geom = geometries.itemSphere;
252
+ else if (modelType === 'box_gold') geom = geometries.itemBox;
253
+ else geom = geometries.itemSphere; // Default
 
254
  const mesh = new THREE.Mesh(geom, mat);
255
+ mesh.position.y = PLAYER_RADIUS; // Default height
256
  mesh.castShadow = true;
257
  return mesh;
258
  }
259
+ function createProjectileMesh() {
260
+ const mat = activeMaterials.projectile; // Use active material
261
+ const mesh = new THREE.Mesh(geometries.projectile, mat);
 
262
  return mesh;
263
  }
264
+
265
  // --- Player Setup ---
266
  function initPlayer() {
267
  console.log("Initializing Player...");
268
  // Visual Mesh
269
  playerMesh = createPlayerMesh();
270
+ // Set initial position high to avoid spawning inside floor
271
+ playerMesh.position.set(0, PLAYER_HEIGHT + 1, 0);
272
  scene.add(playerMesh);
273
+ console.log("Player mesh added to scene at initial pos:", playerMesh.position);
274
 
275
  // Physics Body - Start at center of 0,0 cell, slightly above ground
276
+ const startX = 0;
277
+ const startZ = 0;
278
+ const startY = PLAYER_HEIGHT * 1.5; // Start higher
279
  const playerShape = new CANNON.Sphere(PLAYER_RADIUS);
280
  playerBody = new CANNON.Body({
281
  mass: 70,
282
  shape: playerShape,
283
  position: new CANNON.Vec3(startX, startY, startZ),
284
  linearDamping: 0.95,
285
+ angularDamping: 1.0, // Completely prevent angular rotation from physics
286
+ material: playerMaterial // Use defined material
287
  });
288
  playerBody.allowSleep = false;
289
  playerBody.addEventListener("collide", handlePlayerCollision);
290
  world.addBody(playerBody);
291
+ physicsBodies.set(playerBody.id, playerBody); // Track body using Map
292
  console.log(`Player physics body added at ${startX}, ${startY}, ${startZ}`);
293
 
294
  // Add to sync list
 
299
  // --- Map Generation ---
300
  function generateMap() {
301
  console.log("Generating Map...");
302
+ const wallPhysicsMaterial = world.materials.find(m => m.name === "wall");
303
+ const groundPhysicsMaterial = world.materials.find(m => m.name === "ground");
304
+
305
+ // DEBUG: Only generate the starting cell "0,0"
306
+ const startCoord = "0,0";
307
+ const data = gameData[startCoord];
308
+ if (!data) {
309
+ console.error("CRITICAL: No gameData found for starting cell '0,0'!");
310
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  }
312
+
313
+ const x = 0;
314
+ const z = 0;
315
+ const type = data.type || 'default';
316
+ console.log(`Generating START cell: ${startCoord} (Type: ${type})`);
317
+
318
+ // Create Floor Mesh
319
+ const floorMat = activeMaterials[`floor_${type}`] || activeMaterials.floor_default; // Use debug mats
320
+ const floorMesh = new THREE.Mesh(geometries.floor, floorMat);
321
+ floorMesh.rotation.x = -Math.PI / 2;
322
+ floorMesh.position.set(x * ROOM_SIZE, 0, z * ROOM_SIZE);
323
+ floorMesh.receiveShadow = true; // Floors should receive shadows
324
+ scene.add(floorMesh);
325
+ console.log(`Added floor at ${x},${z}`);
326
+
327
+ // Create Walls (Visual + Physics) for the single cell
328
+ const features = data.features || [];
329
+ const wallDefs = [
330
+ ['north', geometries.wallNS, 0, -0.5], ['south', geometries.wallNS, 0, 0.5],
331
+ ['east', geometries.wallEW, 0.5, 0], ['west', geometries.wallEW, -0.5, 0],
332
+ ];
333
+
334
+ wallDefs.forEach(([dir, geom, xOff, zOff]) => {
335
+ const doorFeature = `door_${dir}`; const pathFeature = `path_${dir}`;
336
+ if (!features.includes(doorFeature) && !features.includes(pathFeature)) {
337
+ const wallX = x * ROOM_SIZE + xOff * ROOM_SIZE;
338
+ const wallZ = z * ROOM_SIZE + zOff * ROOM_SIZE;
339
+ const wallY = WALL_HEIGHT / 2;
340
+
341
+ // Visual Wall (DEBUG)
342
+ const wallMesh = new THREE.Mesh(geom, activeMaterials.wall); // Use debug wall mat
343
+ wallMesh.position.set(wallX, wallY, wallZ);
344
+ wallMesh.castShadow = true; wallMesh.receiveShadow = true;
345
+ scene.add(wallMesh);
346
+
347
+ // Physics Wall
348
+ const wallShape = new CANNON.Box(new CANNON.Vec3(geom.parameters.width / 2, geom.parameters.height / 2, geom.parameters.depth / 2));
349
+ const wallBody = new CANNON.Body({ mass: 0, shape: wallShape, position: new CANNON.Vec3(wallX, wallY, wallZ), material: wallPhysicsMaterial });
350
+ world.addBody(wallBody);
351
+ physicsBodies.set(wallBody.id, wallBody); // Track it
352
+ // console.log(`Added ${dir} wall for cell ${x},${z}`);
353
+ } else {
354
+ console.log(`Skipping ${dir} wall for cell ${x},${z} due to feature.`);
355
+ }
356
+ });
357
+
358
+ // Spawn Items & Monsters based on features for the single cell
359
+ features.forEach(feature => {
360
+ if (feature.startsWith('item_')) {
361
+ const itemName = feature.substring(5).replace(/_/g, ' ');
362
+ if (itemsData[itemName]) spawnItem(itemName, x, z);
363
+ else console.warn(`Item feature found but no data for: ${itemName}`);
364
+ } else if (feature.startsWith('monster_')) {
365
+ const monsterType = feature.substring(8);
366
+ if (monstersData[monsterType]) spawnMonster(monsterType, x, z);
367
+ else console.warn(`Monster feature found but no data for: ${monsterType}`);
368
+ }
369
+ });
370
+
371
+ console.log("Map Generation Complete (Debug Mode - Single Cell).");
372
  }
373
 
374
+ // --- Item/Monster Spawning (Simplified for Pickup 'F') ---
375
  function spawnItem(itemName, gridX, gridZ) {
376
  const itemData = itemsData[itemName];
377
  if (!itemData) return;
 
380
  const y = PLAYER_RADIUS; // Item height
381
 
382
  // Use DEBUG material
383
+ const mesh = createSimpleItemMesh(itemData.model); // Use debug mat via create func
384
+ if (!mesh) return; // Safety check
385
  mesh.position.set(x, y, z);
386
+ mesh.userData = { type: 'item', name: itemName }; // Store data on mesh
387
  mesh.castShadow = true;
388
  scene.add(mesh);
389
 
390
+ // Store item in game state WITHOUT physics body
391
  gameState.items.push({
392
+ id: mesh.uuid, // Use mesh UUID as item ID
393
  name: itemName,
394
  mesh: mesh,
395
  position: mesh.position // Store position for proximity check
396
  });
397
+ console.log(`Spawned item ${itemName} at ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)} (visual only)`);
398
  }
399
 
400
  function spawnMonster(monsterType, gridX, gridZ) {
 
405
  const y = PLAYER_HEIGHT; // Start higher
406
 
407
  // Use DEBUG material
408
+ const mesh = createSimpleMonsterMesh(monsterData.model); // Uses debug mat via create func
409
+ if (!mesh) return; // Safety check
410
+ mesh.position.set(x, y, z); // Initial visual position
411
  mesh.userData = { type: 'monster', monsterType: monsterType };
412
  scene.add(mesh);
413
 
414
  // Physics Body
415
+ const shape = new CANNON.Sphere(PLAYER_RADIUS * 0.8);
416
  const body = new CANNON.Body({
417
+ mass: 10, shape: shape, position: new CANNON.Vec3(x, y, z),
418
+ linearDamping: 0.8, angularDamping: 0.9,
 
 
 
419
  material: world.materials.find(m => m.name === "monster") || new CANNON.Material("monster")
420
  });
421
  body.allowSleep = true;
422
+ // Store reference to mesh and HP on body's userData
423
  body.userData = { type: 'monster', monsterType: monsterType, mesh: mesh, hp: monsterData.hp };
424
  world.addBody(body);
425
 
426
  gameState.monsters.push({ id: body.id, type: monsterType, hp: monsterData.hp, body: body, mesh: mesh });
427
  meshesToSync.push({ mesh: mesh, body: body });
428
+ physicsBodies.set(body.id, body); // Use map for tracking
429
+ console.log(`Spawned monster ${monsterType} at ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)}`);
430
  }
431
 
432
 
433
+ // --- Input Handling (QWEASDZXC + Jump 'X' + F + Space) ---
434
+ function setupInputListeners() { /* ... same ... */
435
  console.log("Setting up input listeners.");
436
+ window.addEventListener('keydown', (event) => { keysPressed[event.key.toLowerCase()] = true; keysPressed[event.code] = true; if (['space', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', 'keyx', 'keyf'].includes(event.code.toLowerCase())) { event.preventDefault(); }});
437
+ window.addEventListener('keyup', (event) => { keysPressed[event.key.toLowerCase()] = false; keysPressed[event.code] = false; });
 
 
 
 
 
 
 
 
 
 
438
  }
439
 
440
  function handleInput(deltaTime) {
441
  if (!playerBody) return;
442
 
443
  const moveSpeed = PLAYER_SPEED;
444
+ // Correct forward/backward/strafe directions relative to world axes
445
+ // Assume +Z is SOUTH, -Z is NORTH
446
+ // Assume +X is EAST, -X is WEST
447
+ let forceX = 0;
448
+ let forceZ = 0;
449
+
450
+ // Forward (-Z) / Backward (+Z)
451
+ if (keysPressed['w']) forceZ -= 1; // W = North = -Z
452
+ if (keysPressed['s']) forceZ += 1; // S = South = +Z
453
+
454
+ // Strafe Left (-X) / Right (+X)
455
+ if (keysPressed['a']) forceX -= 1; // A = West = -X
456
+ if (keysPressed['d']) forceX += 1; // D = East = +X
457
+
458
+ // Diagonals - combine basic directions
459
+ if (keysPressed['q']) { forceZ -= 0.707; forceX -= 0.707; } // Q = NW
460
+ if (keysPressed['e']) { forceZ -= 0.707; forceX += 0.707; } // E = NE
461
+ if (keysPressed['z']) { forceZ += 0.707; forceX -= 0.707; } // Z = SW
462
+ if (keysPressed['c']) { forceZ += 0.707; forceX += 0.707; } // C = SE
 
463
 
464
  // --- Calculate final velocity vector ---
465
+ // We set velocity directly for more responsive control than forces
466
+ const targetVelocity = new CANNON.Vec3(0, playerBody.velocity.y, 0); // Preserve Y velocity
 
 
 
 
467
 
468
+ if (forceX !== 0 || forceZ !== 0) {
469
+ const moveVec = new THREE.Vector2(forceX, forceZ);
470
+ if (moveVec.lengthSq() > 1.0) { // Normalize only if combined magnitude > 1
471
+ moveVec.normalize();
472
+ }
473
+ targetVelocity.x = moveVec.x * moveSpeed;
474
+ targetVelocity.z = moveVec.y * moveSpeed;
475
 
476
+ // --- Rotation ---
477
+ // Rotate player mesh to face movement direction
478
+ // Calculate angle from positive Z axis (adjust if your model faces differently)
479
+ const angle = Math.atan2(targetVelocity.x, targetVelocity.z);
480
  const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
481
+ // Slerp for smooth rotation
482
+ playerMesh.quaternion.slerp(targetQuaternion, 0.15); // Adjust 0.15 for responsiveness
483
 
484
  } else {
485
+ // No movement keys pressed - rely on linear damping to stop
486
+ // Or force stop X/Z velocity:
487
+ targetVelocity.x = 0;
488
+ targetVelocity.z = 0;
489
  }
490
 
491
+ playerBody.velocity.x = targetVelocity.x;
492
+ playerBody.velocity.z = targetVelocity.z;
493
+ // Y velocity is controlled by gravity + jump impulse
494
+
495
+ // --- Jump (X) ---
496
+ if (keysPressed['x'] || keysPressed['keyx']) { // Check code too
497
+ // !! Basic jump - Needs ground check via raycast or contact materials !!
498
+ // Add a simple cooldown or only allow if Y velocity is low
499
+ if (Math.abs(playerBody.velocity.y) < 0.5) { // Crude check if mostly grounded
500
+ console.log("JUMP!");
501
+ addLog("Jump!", "info");
502
+ // Apply impulse upwards
503
+ playerBody.applyImpulse(new CANNON.Vec3(0, PLAYER_JUMP_IMPULSE, 0), playerBody.position);
504
  }
505
+ keysPressed['x'] = false; keysPressed['keyx'] = false; // Consume jump input
 
506
  }
507
 
508
  // --- Pickup (F) ---
509
+ if (keysPressed['f'] || keysPressed['keyf']) {
510
  pickupNearbyItem();
511
+ keysPressed['f'] = false; keysPressed['keyf'] = false; // Consume pickup input
512
  }
513
 
514
  // --- Fire (Space) ---
 
523
  if (!playerBody) return;
524
  const playerPos = playerBody.position;
525
  let pickedUp = false;
526
+ let closestItemIndex = -1;
527
+ let minDistanceSq = PICKUP_RADIUS_SQ; // Use squared distance
528
 
529
+ // Find the closest item within radius
530
+ for (let i = 0; i < gameState.items.length; i++) {
531
  const item = gameState.items[i];
532
+ const distanceSq = playerPos.distanceSquared(item.position);
533
+ if (distanceSq < minDistanceSq) {
534
+ minDistanceSq = distanceSq;
535
+ closestItemIndex = i;
 
 
 
 
 
 
 
 
 
 
 
 
536
  }
537
  }
538
+
539
+ // Pick up the closest item if found
540
+ if (closestItemIndex > -1) {
541
+ const item = gameState.items[closestItemIndex];
542
+ if (!gameState.inventory.includes(item.name)) {
543
+ gameState.inventory.push(item.name);
544
+ addLog(`Picked up ${item.name}!`, "pickup");
545
+ updateInventoryDisplay();
546
+
547
+ // Remove item visually and from state
548
+ if(item.mesh.parent) scene.remove(item.mesh);
549
+ gameState.items.splice(closestItemIndex, 1);
550
+ pickedUp = true;
551
+ } else {
552
+ addLog(`Already have ${item.name}.`, "info");
553
+ }
554
+ }
555
+
556
  if (!pickedUp) {
557
  addLog("Nothing nearby to pick up.", "info");
558
  }
559
  }
560
 
561
 
562
+ // --- Combat (Projectile logic remains similar) ---
563
+ function fireProjectile() {
564
  if (!playerBody || !playerMesh) return;
565
  addLog("Pew!", "combat");
566
  const projectileMesh = createProjectileMesh();
567
  const projectileShape = new CANNON.Sphere(PROJECTILE_RADIUS);
568
  const projectileBody = new CANNON.Body({ mass: 0.1, shape: projectileShape, linearDamping: 0.01, angularDamping: 0.01 });
569
  projectileBody.addEventListener("collide", handleProjectileCollision);
570
+
571
+ // Calculate start position and velocity based on player's *current* rotation
572
  const offsetDistance = PLAYER_RADIUS + PROJECTILE_RADIUS + 0.1;
573
+ const direction = new THREE.Vector3(0, 0, 1); // Base direction +Z
574
+ direction.applyQuaternion(playerMesh.quaternion); // Rotate based on player mesh
575
+
576
  const startPos = new CANNON.Vec3().copy(playerBody.position).vadd(
577
+ new CANNON.Vec3(direction.x, 0, direction.z).scale(offsetDistance) // Offset horizontally
578
  );
579
+ // Adjust start Y based on player body center + visual model height
580
+ startPos.y = playerBody.position.y; // Fire from player center height
581
+
582
  projectileBody.position.copy(startPos);
583
  projectileMesh.position.copy(startPos);
584
+
585
+ // Velocity in player facing direction
586
  projectileBody.velocity = new CANNON.Vec3(direction.x, 0, direction.z).scale(PROJECTILE_SPEED);
587
+
588
  scene.add(projectileMesh);
589
  world.addBody(projectileBody);
590
+ const projectileData = { mesh: projectileMesh, body: projectileBody, lifetime: 2.0 }; // Shorter lifetime
591
  meshesToSync.push(projectileData);
592
  projectiles.push(projectileData);
593
+ physicsBodies.set(projectileBody.id, projectileBody); // Track
594
+ projectileBody.userData = { type: 'projectile', data: projectileData };
595
+ projectileMesh.userData = { type: 'projectile', data: projectileData }; // No body ref needed on mesh
596
  }
597
 
598
  // --- Collision Handling ---
599
+ function handlePlayerCollision(event) {
600
  const otherBody = event.body;
601
+ if (!otherBody || !otherBody.userData || !playerBody) return;
602
 
603
+ // Player <-> Monster (Example: Simple damage, could add knockback)
 
 
604
  if (otherBody.userData.type === 'monster') {
605
+ // Check for cooldown before applying damage again?
606
+ console.log("Player collided with monster", otherBody.id);
607
+ // gameState.stats.hp -= 1;
608
+ // addLog(`Hit by ${otherBody.userData.monsterType || 'monster'}! HP: ${gameState.stats.hp}`, "combat");
609
+ // updateStatsDisplay();
610
+ // if (gameState.stats.hp <= 0) { gameOver("Defeated by a monster!"); }
611
+ // Apply small impulse away from monster
612
+ const impulse = playerBody.position.vsub(otherBody.position).unit().scale(20); // Knockback force
613
+ playerBody.applyImpulse(impulse, playerBody.position);
614
  }
615
+ // Player <-> Wall (Handled by physics engine)
616
+ // Player <-> Item (Handled by 'F' key)
617
  }
618
 
619
+ function handleProjectileCollision(event) {
620
  const projectileBody = event.target;
621
  const otherBody = event.body;
622
+ if (!projectileBody?.userData || !otherBody?.userData) return; // Null checks
623
 
624
  const projectileData = projectileBody.userData.data;
625
+ let shouldRemoveProjectile = true; // Assume removal unless hitting player
626
 
627
  if (otherBody.userData.type === 'monster') {
628
  const monsterId = otherBody.id;
629
  const monsterIndex = gameState.monsters.findIndex(m => m.id === monsterId);
630
  if (monsterIndex > -1) {
631
  const monster = gameState.monsters[monsterIndex];
632
+ const damage = gameState.stats.strength + Math.floor(Math.random() * 3); // Add randomness
633
  monster.hp -= damage;
634
+ otherBody.userData.hp = monster.hp;
635
  addLog(`Hit ${otherBody.userData.monsterType} for ${damage} damage! (HP: ${monster.hp})`, "combat");
636
+
637
+ // Apply impulse to monster
638
+ const impulseDir = projectileBody.velocity.unit();
639
+ otherBody.applyImpulse(impulseDir.scale(damage * 5), projectileBody.position); // Knockback scales with damage
640
+
641
+
642
  if (monster.hp <= 0) {
643
  addLog(`Defeated ${otherBody.userData.monsterType}!`, "info");
644
+ // Safely remove monster after physics step using setTimeout
645
+ setTimeout(() => {
646
+ if(monster.mesh.parent) scene.remove(monster.mesh);
647
+ if(world.bodies.includes(monster.body)) world.removeBody(monster.body);
648
+ meshesToSync = meshesToSync.filter(sync => sync.body.id !== monster.body.id);
649
+ physicsBodies.delete(monster.body.id);
650
+ gameState.monsters = gameState.monsters.filter(m => m.id !== monsterId);
651
+ }, 0);
652
  }
653
  }
654
+ } else if (otherBody === playerBody) {
655
+ shouldRemoveProjectile = false; // Don't destroy projectile if it hits the player who fired it
656
+ console.log("Projectile hit player - ignored");
657
+ } else if (otherBody.mass === 0) {
658
+ // Hit a static object like a wall
659
+ console.log("Projectile hit wall/static");
660
+ // Optional: Add impact effect
661
  }
662
 
663
+
664
+ if (shouldRemoveProjectile) {
665
+ // Schedule removal might be safer than immediate
666
+ setTimeout(() => removeProjectile(projectileData), 0);
667
  }
668
  }
669
 
670
+ function removeProjectile(projectileData) {
671
  if (!projectileData) return;
672
  const index = projectiles.indexOf(projectileData);
673
+ if (index === -1) return;
674
 
675
+ if (projectileData.mesh?.parent) scene.remove(projectileData.mesh);
676
+ if (projectileData.body && world.bodies.includes(projectileData.body)) world.removeBody(projectileData.body);
 
 
677
 
678
+ meshesToSync = meshesToSync.filter(sync => sync.body?.id !== projectileData.body?.id);
679
+ if (projectileData.body) physicsBodies.delete(projectileData.body.id);
680
  projectiles.splice(index, 1);
681
  }
682
 
683
+
684
  // --- Monster AI ---
685
+ function updateMonsters(deltaTime) {
686
+ const agroRangeSq = (ROOM_SIZE * 2) ** 2; // Increased range
687
+ if(!playerBody) return;
688
 
689
  gameState.monsters.forEach(monster => {
690
+ if (!monster || !monster.body || monster.hp <= 0) return; // Skip dead or removed monsters
691
+
692
  const monsterPos = monster.body.position;
693
  const playerPos = playerBody.position;
694
  const distanceSq = playerPos.distanceSquared(monsterPos);
695
 
696
+ if (distanceSq < agroRangeSq) { // If player is close
697
  const direction = playerPos.vsub(monsterPos);
698
+ direction.y = 0; // Ignore height difference for movement plan
699
+ if (distanceSq > (PLAYER_RADIUS * 2)**2 && direction.lengthSquared() > 0.1) { // If not too close and direction is valid
700
  direction.normalize();
701
  const monsterData = monstersData[monster.type];
702
+ const speed = monsterData?.speed || 1;
703
+
704
+ // Apply velocity for chasing
 
705
  monster.body.velocity.x = direction.x * speed;
706
  monster.body.velocity.z = direction.z * speed;
707
 
708
  // Rotation
709
  const angle = Math.atan2(direction.x, direction.z);
710
  const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
711
+ monster.mesh.quaternion.slerp(targetQuaternion, 0.1);
712
+ } else { // Too close or direction invalid, stop horizontal movement
713
+ monster.body.velocity.x = 0;
714
+ monster.body.velocity.z = 0;
715
+ // TODO: Add attack logic here if close enough
716
+ }
717
+ } else { // Player too far, stop moving
718
  monster.body.velocity.x = 0;
719
  monster.body.velocity.z = 0;
720
  }
721
+ // Wake up body if needed (should be awake if chasing)
722
+ if(monster.body.sleepState === CANNON.Body.SLEEPING) monster.body.wakeUp();
723
  });
724
  }
725
 
726
+ // --- UI Update Functions ---
727
+ function updateUI() { updateStatsDisplay(); updateInventoryDisplay(); }
728
+ function updateStatsDisplay() { /* ... same ... */
729
+ let statsHTML = ''; statsHTML += `<span>HP: ${gameState.stats.hp}/${gameState.stats.maxHp}</span>`; statsHTML += `<span>Str: ${gameState.stats.strength}</span>`; statsHTML += `<span>Wis: ${gameState.stats.wisdom}</span>`; statsHTML += `<span>Cor: ${gameState.stats.courage}</span>`; statsElement.innerHTML = statsHTML;
 
 
 
 
 
 
 
 
 
730
  }
731
+ function updateInventoryDisplay() { /* ... same ... */
732
+ let inventoryHTML = ''; if (gameState.inventory.length === 0) { inventoryHTML += '<em>Empty</em>'; } 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>`; }); } inventoryElement.innerHTML = inventoryHTML;
 
 
 
733
  }
734
+ function addLog(message, type = "info") { /* ... same ... */
735
+ const p = document.createElement('p'); p.classList.add(type); p.textContent = `[${new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}] ${message}`; logElement.appendChild(p); logElement.scrollTop = logElement.scrollHeight;
 
 
 
 
736
  }
737
 
 
738
  // --- Game Over ---
739
+ function gameOver(reason) { /* ... same ... */
740
+ addLog(`GAME OVER: ${reason}`, "error"); console.log("Game Over:", reason);
 
741
  gameLoopActive = false; // Stop the game loop
742
+ const restartButton = document.createElement('button'); restartButton.textContent = "RESTART GAME"; restartButton.style.cssText = `position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px 40px; font-size: 2em; cursor: pointer; z-index: 1000; background-color: #ffc107; border: none; border-radius: 5px; color: #333; font-family: 'Courier New', monospace;`;
743
+ restartButton.onclick = () => { if (restartButton.parentNode) restartButton.parentNode.removeChild(restartButton); init(); }; // Re-initialize
744
+ sceneContainer.appendChild(restartButton);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745
  }
746
 
 
747
  // --- Main Game Loop ---
748
+ let lastTimestamp = 0;
749
+ function animate(timestamp) {
750
+ if (!gameLoopActive) return;
751
+ animationFrameId = requestAnimationFrame(animate);
752
+
753
+ const deltaTime = (timestamp - lastTimestamp) * 0.001;
754
+ lastTimestamp = timestamp;
755
+ const dtClamped = Math.min(deltaTime, 1 / 20); // Clamp delta time (max 20 FPS step)
756
+
757
+ if (!world || !playerBody || !scene || !camera || !renderer) {
758
+ console.error("Core component missing, stopping loop.");
759
+ gameLoopActive = false;
760
+ return;
761
+ }
762
 
763
+ // 1. Input
764
  handleInput(dtClamped);
765
 
766
+ // 2. AI
767
  updateMonsters(dtClamped);
768
 
769
+ // 3. Physics Step
770
+ try { world.step(dtClamped); }
771
+ catch (e) { console.error("Physics step error:", e); gameLoopActive = false; return; } // Stop loop on error
 
 
 
 
 
772
 
773
+ // 4. Projectiles Update
774
  for (let i = projectiles.length - 1; i >= 0; i--) {
775
  const p = projectiles[i];
776
+ if (p) { p.lifetime -= dtClamped; if (p.lifetime <= 0) removeProjectile(p); }
 
 
 
 
 
777
  }
778
 
779
+ // 5. Sync Visuals
780
  meshesToSync.forEach(item => {
781
+ if (item?.body && item?.mesh && item.mesh.parent) { // Check existence
 
782
  item.mesh.position.copy(item.body.position);
783
  item.mesh.quaternion.copy(item.body.quaternion);
 
 
 
 
784
  }
785
  });
786
 
787
  // 6. Update Camera
788
+ if (playerBody && camera) {
789
  const targetCameraPos = new THREE.Vector3(
790
  playerBody.position.x,
791
  CAMERA_Y_OFFSET,
792
+ playerBody.position.z // Look straight down from above player
793
  );
794
+ camera.position.lerp(targetCameraPos, 0.1); // Smooth follow
795
+ // Camera already looking down due to initial setup / rotation
796
+ // camera.lookAt(playerBody.position.x, 0, playerBody.position.z); // Keep looking at player's feet
 
797
  }
798
 
799
+ // 7. Physics Debugger (Optional)
800
+ // if (cannonDebugger) cannonDebugger.update();
801
 
802
+ // 8. Render
 
 
 
 
 
803
  renderer.render(scene, camera);
804
+ }
805
 
806
+ // --- Window Resize ---
807
+ function onWindowResize() {
808
+ if (!renderer || !camera) return;
809
+ const width = sceneContainer.clientWidth;
810
+ const height = sceneContainer.clientHeight;
811
+ camera.aspect = width / height;
812
+ camera.updateProjectionMatrix();
813
+ renderer.setSize(width, height);
814
+ console.log("Resized");
815
  }
816
 
817
  // --- Start Game ---