Certainly! I'll help you remove the green wireframe sphere around the player and address the collision bug that causes the player to get stuck when interacting with other objects. Below are the steps and the updated code to achieve this:
Remove the Green Wireframe Sphere:
The green wireframe sphere (sphereHelper) is used for debugging purposes to visualize the player's collision boundary. To remove it, you can simply comment out or delete the relevant code section.
Fix the Collision Detection Bug:
The current collision detection separately checks collisions along the X and Z axes. This approach can sometimes cause the player to get stuck, especially when moving diagonally or backward. To fix this, we'll modify the collision detection to consider both axes together, ensuring smoother movement and preventing the player from getting stuck.
Key Changes:
Combined Collision Check: Instead of checking X and Z axes separately, we'll check the intended new position for any collisions before applying the movement.
Adjust Player Sphere Radius: Ensure the player's collision sphere isn't too large, which can cause unnecessary collisions.
Simplify Movement Logic: Streamline the movement and collision response for better performance and reliability.
Below is the updated HTML and JavaScript code with these changes implemented:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First-Person Shooter Game with Enhanced Collision Detection</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #87ceeb;
cursor: crosshair;
}
canvas {
display: block;
}
#instructions {
position: absolute;
top: 50%;
width: 100%;
text-align: center;
color: white;
font-family: Arial, sans-serif;
font-size: 24px;
user-select: none;
cursor: pointer;
transform: translateY(-50%);
z-index: 1; /* Ensure it's above the canvas */
}
/* ---------- Scope Overlay Styles ---------- */
#scope {
position: absolute;
top: 50%;
left: 50%;
width: 40px; /* Smaller size for minimalism */
height: 40px; /* Smaller size for minimalism */
margin-left: -20px; /* Half of width to center */
margin-top: -20px; /* Half of height to center */
pointer-events: none; /* Allow clicks to pass through */
z-index: 2; /* Above instructions */
}
/* Crosshair Horizontal Line */
#scope .crosshair-horizontal {
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 2px; /* Thin line */
background: rgba(255, 255, 255, 0.7);
transform: translateY(-50%);
}
/* Crosshair Vertical Line */
#scope .crosshair-vertical {
position: absolute;
top: 0;
left: 50%;
width: 2px; /* Thin line */
height: 100%;
background: rgba(255, 255, 255, 0.7);
transform: translateX(-50%);
}
</style>
<!-- Import Map to resolve 'three' and 'tween.js' modules -->
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.152.0/build/three.module.js",
"tween.js": "https://unpkg.com/@tweenjs/tween.js@18.6.4/dist/tween.esm.js"
}
}
</script>
</head>
<body>
<div id="instructions">
Click to Play<br>
W/A/S/D to Move | Mouse to Look | Click to Shoot<br>
Spacebar to Jump | Ctrl to Crouch | Shift to Run
</div>
<!-- Scope Overlay -->
<div id="scope">
<div class="crosshair-horizontal"></div>
<div class="crosshair-vertical"></div>
</div>
<script type="module">
'use strict';
// Import Three.js, PointerLockControls, and TWEEN.js as ES6 modules using import map
import * as THREE from 'three';
import { PointerLockControls } from 'https://cdn.jsdelivr.net/npm/three@0.152.0/examples/jsm/controls/PointerLockControls.js';
import TWEEN from 'tween.js'; // Corrected import for TWEEN.js
// Constants for player's height and collision radius
const standingHeight = 10.0;
const crouchHeight = 7.0;
const playerRadius = 4.0; // Adjusted radius to prevent sticking
// Setup Scene, Camera, and Renderer
const scene = new THREE.Scene();
// Set the sky to a solid blue color
scene.background = new THREE.Color(0x87ceeb); // Sky Blue
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio( window.devicePixelRatio );
renderer.shadowMap.enabled = true; // Enable shadows
document.body.appendChild(renderer.domElement);
// ---------- Add Lighting ----------
// Hemisphere Light to simulate ambient light from the sky and ground
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 1.0);
hemiLight.position.set(0, 200, 0);
scene.add(hemiLight);
// Directional Light to simulate the sun
const sunLight = new THREE.DirectionalLight(0xffffff, 0.8);
sunLight.position.set(100, 200, 100); // Position above and to the side
sunLight.castShadow = true;
sunLight.shadow.camera.top = 200;
sunLight.shadow.camera.bottom = -100;
sunLight.shadow.camera.left = -120;
sunLight.shadow.camera.right = 120;
scene.add(sunLight);
// ---------- Add Sun ----------
// Create a visible sun as a bright emissive sphere
const sunGeometry = new THREE.SphereGeometry(20, 32, 32);
const sunMaterial = new THREE.MeshStandardMaterial({
color: 0xffff00,
emissive: 0xffff00,
emissiveIntensity: 1
});
const sun = new THREE.Mesh(sunGeometry, sunMaterial);
sun.position.copy(sunLight.position);
scene.add(sun);
// ---------- Add Clouds ----------
const clouds = [];
const cloudMaterial = new THREE.MeshLambertMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.6,
depthWrite: false
});
// Function to create a single cloud
function createCloud() {
const cloudGroup = new THREE.Group();
const cloudCount = 5; // Number of spheres per cloud
for (let i = 0; i < cloudCount; i++) {
const sphereGeometry = new THREE.SphereGeometry(10, 16, 16);
const sphere = new THREE.Mesh(sphereGeometry, cloudMaterial);
sphere.position.set(
Math.random() * 20 - 10, // X position relative to cloud group
Math.random() * 5 - 2.5, // Y position relative to cloud group
Math.random() * 20 - 10 // Z position relative to cloud group
);
cloudGroup.add(sphere);
}
return cloudGroup;
}
// Create multiple clouds and position them randomly in the sky
for (let i = 0; i < 20; i++) { // Number of clouds
const cloud = createCloud();
cloud.position.set(
Math.random() * 800 - 400, // X position in the world
Math.random() * 100 + 50, // Y position (altitude)
Math.random() * 800 - 400 // Z position in the world
);
scene.add(cloud);
clouds.push(cloud);
}
// ---------- Add Green Ground ----------
const groundMaterial = new THREE.MeshLambertMaterial({
color: 0x228B22 // Forest Green
});
const groundGeometry = new THREE.PlaneGeometry(1000, 1000);
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = - Math.PI / 2; // Rotate to make it horizontal
ground.receiveShadow = true; // Allow ground to receive shadows
scene.add(ground);
// ---------- Add Trees ----------
const trees = [];
const treeMaterialTrunk = new THREE.MeshStandardMaterial({ color: 0x8B4513 }); // Brown for trunks
const treeMaterialFoliage = new THREE.MeshStandardMaterial({ color: 0x006400 }); // Dark Green for foliage
// Function to create a single tree
function createTree() {
const tree = new THREE.Group();
// Create trunk
const trunkGeometry = new THREE.CylinderGeometry(1, 1, 10, 8);
const trunk = new THREE.Mesh(trunkGeometry, treeMaterialTrunk);
trunk.position.y = 5; // Half of trunk height
trunk.castShadow = true;
trunk.receiveShadow = true;
tree.add(trunk);
// Create foliage
const foliageGeometry = new THREE.ConeGeometry(5, 20, 8);
const foliage = new THREE.Mesh(foliageGeometry, treeMaterialFoliage);
foliage.position.y = 15; // Position on top of trunk
foliage.castShadow = true;
foliage.receiveShadow = true;
tree.add(foliage);
return tree;
}
// Create multiple trees and position them randomly on the ground
for (let i = 0; i < 100; i++) { // Number of trees
const tree = createTree();
tree.position.set(
Math.random() * 800 - 400, // X position in the world
0, // Y position on the ground
Math.random() * 800 - 400 // Z position in the world
);
scene.add(tree);
trees.push(tree);
}
// ---------- Add Some Red Cubes as Targets ----------
const boxGeometry = new THREE.BoxGeometry(20, 20, 20);
const boxMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 }); // Red color
const targets = [];
for (let i = 0; i < 20; i++) {
const box = new THREE.Mesh(boxGeometry, boxMaterial);
box.position.set(
Math.random() * 800 - 400,
10,
Math.random() * 800 - 400
);
box.castShadow = true;
box.receiveShadow = true;
scene.add(box);
targets.push(box);
}
// ---------- Add a House with Windows and Doors ----------
function createHouse() {
const house = new THREE.Group();
// ----- Walls -----
const wallsMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513 }); // Brown color for walls
const wallsGeometry = new THREE.BoxGeometry(100, 60, 100);
const walls = new THREE.Mesh(wallsGeometry, wallsMaterial);
walls.castShadow = true;
walls.receiveShadow = true;
walls.position.y = 30; // Raise walls to sit on the ground
house.add(walls);
// ----- Roof -----
const roofMaterial = new THREE.MeshStandardMaterial({ color: 0xB22222 }); // Firebrick color for roof
const roofGeometry = new THREE.ConeGeometry(70, 30, 4); // Square base
const roof = new THREE.Mesh(roofGeometry, roofMaterial);
roof.rotation.y = Math.PI / 4; // Rotate to align with walls
roof.position.y = 60; // Position atop the walls
roof.castShadow = true;
roof.receiveShadow = true;
house.add(roof);
// ----- Door -----
const doorMaterial = new THREE.MeshStandardMaterial({ color: 0x654321 }); // Dark brown for door
const doorGeometry = new THREE.BoxGeometry(20, 35, 5);
const door = new THREE.Mesh(doorGeometry, doorMaterial);
door.position.set(0, 17.5, 52.51); // Position on the front face of walls
door.castShadow = true;
door.receiveShadow = true;
house.add(door);
// ----- Windows -----
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0xADD8E6, // Light blue for windows
transparent: true,
opacity: 0.6
});
const windowGeometry = new THREE.BoxGeometry(15, 15, 2);
// Front Window
const frontWindow = new THREE.Mesh(windowGeometry, windowMaterial);
frontWindow.position.set(-30, 30, 52.51); // Left front window
house.add(frontWindow);
const frontWindow2 = new THREE.Mesh(windowGeometry, windowMaterial);
frontWindow2.position.set(30, 30, 52.51); // Right front window
house.add(frontWindow2);
// Back Window
const backWindow = new THREE.Mesh(windowGeometry, windowMaterial);
backWindow.position.set(-30, 30, -52.51); // Left back window
house.add(backWindow);
const backWindow2 = new THREE.Mesh(windowGeometry, windowMaterial);
backWindow2.position.set(30, 30, -52.51); // Right back window
house.add(backWindow2);
// ----- Side Windows -----
const sideWindow = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow.position.set(52.51, 30, 30); // Right side window
sideWindow.rotation.y = Math.PI / 2;
house.add(sideWindow);
const sideWindow2 = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow2.position.set(52.51, 30, -30); // Right side window
sideWindow2.rotation.y = Math.PI / 2;
house.add(sideWindow2);
const sideWindow3 = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow3.position.set(-52.51, 30, 30); // Left side window
sideWindow3.rotation.y = Math.PI / 2;
house.add(sideWindow3);
const sideWindow4 = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow4.position.set(-52.51, 30, -30); // Left side window
sideWindow4.rotation.y = Math.PI / 2;
house.add(sideWindow4);
return house;
}
// Create and position the house
const house = createHouse();
house.position.set(0, 0, -200); // Position the house 200 units behind the starting point
scene.add(house);
// ---------- Pointer Lock Controls ----------
const controls = new PointerLockControls(camera, document.body);
const instructions = document.getElementById('instructions');
instructions.addEventListener('click', () => {
controls.lock();
}, false);
controls.addEventListener('lock', () => {
instructions.style.display = 'none';
});
controls.addEventListener('unlock', () => {
instructions.style.display = '';
});
scene.add(controls.getObject());
// ---------- Initialize Player's Y Position ----------
controls.getObject().position.y = standingHeight;
// ---------- Movement Variables ----------
const move = {
forward: false,
backward: false,
left: false,
right: false,
run: false
};
let velocity = new THREE.Vector3();
let direction = new THREE.Vector3();
const walkSpeed = 400.0; // Units per second
const runSpeed = 700.0; // Units per second
let currentSpeed = walkSpeed;
// ---------- Jumping and Gravity Variables ----------
const gravity = 2000.0; // Units per second squared
let isOnGround = true;
let verticalVelocity = 0.0;
// ---------- Crouch Variables ----------
let isCrouching = false;
// ---------- Shooting Variables ----------
let isShooting = false; // Flag to indicate if shooting is active
const fireRate = 10; // Bullets per second
const shootInterval = 1 / fireRate; // Seconds between shots
let shootTimer = 0; // Timer to track shooting
// ---------- Event Listeners for Key Presses ----------
const onKeyDown = function (event) {
switch (event.code) {
case 'KeyW':
case 'ArrowUp':
move.forward = true;
break;
case 'KeyA':
case 'ArrowLeft':
move.left = true;
break;
case 'KeyS':
case 'ArrowDown':
move.backward = true;
break;
case 'KeyD':
case 'ArrowRight':
move.right = true;
break;
case 'Space':
if (isOnGround && !isCrouching) {
verticalVelocity = 600; // Initial jump velocity (positive for upward)
isOnGround = false;
}
break;
case 'ShiftLeft':
case 'ShiftRight':
move.run = true;
break;
case 'ControlLeft':
case 'ControlRight':
toggleCrouch();
break;
}
};
const onKeyUp = function (event) {
switch (event.code) {
case 'KeyW':
case 'ArrowUp':
move.forward = false;
break;
case 'KeyA':
case 'ArrowLeft':
move.left = false;
break;
case 'KeyS':
case 'ArrowDown':
move.backward = false;
break;
case 'KeyD':
case 'ArrowRight':
move.right = false;
break;
case 'ShiftLeft':
case 'ShiftRight':
move.run = false;
break;
// Note: Removed handling for 'Control' key on keyup since we're using toggle
}
};
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
// ---------- Event Listeners for Mouse Presses ----------
window.addEventListener('mousedown', (event) => {
if (event.button === 0 && controls.isLocked === true) { // Left mouse button
isShooting = true;
}
}, false);
window.addEventListener('mouseup', (event) => {
if (event.button === 0 && controls.isLocked === true) { // Left mouse button
isShooting = false;
}
}, false);
// ---------- Crouch Toggle Function ----------
function toggleCrouch() {
if (isCrouching) {
// Stand up
isCrouching = false;
// Smoothly interpolate camera position back to standing
new TWEEN.Tween(controls.getObject().position)
.to({ y: standingHeight }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
// Smoothly interpolate gun position back to standing
new TWEEN.Tween(gun.position)
.to({ y: -1 }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
} else {
// Crouch down
isCrouching = true;
// Smoothly interpolate camera position to crouch
new TWEEN.Tween(controls.getObject().position)
.to({ y: crouchHeight }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
// Smoothly interpolate gun position to crouch
new TWEEN.Tween(gun.position)
.to({ y: -1.5 }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
}
}
// ---------- Bullet Array ----------
const bullets = [];
const bulletSpeed = 1000; // Units per second
const bulletGeometry = new THREE.SphereGeometry(0.5, 8, 8);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 }); // Yellow bullets
// ---------- Shooting Mechanism ----------
const shoot = () => {
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
bullet.position.copy(controls.getObject().position);
bullet.position.y -= 1; // Adjust bullet's y-position to align with gun
// Calculate direction
const vector = new THREE.Vector3(0, 0, -1);
vector.applyQuaternion(camera.quaternion);
bullet.velocity = vector.clone().multiplyScalar(bulletSpeed);
scene.add(bullet);
bullets.push(bullet);
};
// ---------- Gun Setup (AK-74 Model) ----------
// Create a more detailed AK-74 model using basic geometries
const gun = new THREE.Group();
// ----- Receiver -----
const receiverGeometry = new THREE.BoxGeometry(1, 0.5, 1.5);
const receiverMaterial = new THREE.MeshStandardMaterial({ color: 0x444444 });
const receiver = new THREE.Mesh(receiverGeometry, receiverMaterial);
receiver.position.set(0, 0, -0.75);
receiver.castShadow = true;
receiver.receiveShadow = true;
gun.add(receiver);
// ----- Barrel -----
const barrelGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 8);
const barrelMaterial = new THREE.MeshStandardMaterial({ color: 0x555555 });
const barrel = new THREE.Mesh(barrelGeometry, barrelMaterial);
barrel.rotation.x = Math.PI / 2;
barrel.position.set(0, 0, -2);
barrel.castShadow = true;
barrel.receiveShadow = true;
gun.add(barrel);
// ----- Handguard -----
const handguardGeometry = new THREE.BoxGeometry(0.3, 0.3, 1.5);
const handguardMaterial = new THREE.MeshStandardMaterial({ color: 0x666666 });
const handguard = new THREE.Mesh(handguardGeometry, handguardMaterial);
handguard.position.set(0, 0.5, -1.5);
handguard.castShadow = true;
handguard.receiveShadow = true;
gun.add(handguard);
// ----- Magazine -----
const magazineGeometry = new THREE.BoxGeometry(0.5, 1, 0.5);
const magazineMaterial = new THREE.MeshStandardMaterial({ color: 0x000000 });
const magazine = new THREE.Mesh(magazineGeometry, magazineMaterial);
magazine.position.set(0, -0.75, -0.75);
magazine.castShadow = true;
magazine.receiveShadow = true;
gun.add(magazine);
// ----- Stock -----
const stockGeometry = new THREE.BoxGeometry(0.2, 1, 0.2);
const stockMaterial = new THREE.MeshStandardMaterial({ color: 0x444444 });
const stock = new THREE.Mesh(stockGeometry, stockMaterial);
stock.position.set(-0.6, -0.4, 0.3);
stock.castShadow = true;
stock.receiveShadow = true;
gun.add(stock);
// ----- Front Sight -----
const frontSightGeometry = new THREE.BoxGeometry(0.05, 0.05, 0.2);
const frontSightMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const frontSight = new THREE.Mesh(frontSightGeometry, frontSightMaterial);
frontSight.position.set(0, 0.25, -3);
frontSight.castShadow = true;
frontSight.receiveShadow = true;
gun.add(frontSight);
// ----- Rear Sight -----
const rearSightGeometry = new THREE.BoxGeometry(0.1, 0.1, 0.2);
const rearSightMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const rearSight = new THREE.Mesh(rearSightGeometry, rearSightMaterial);
rearSight.position.set(-0.3, 0.25, -0.5);
rearSight.castShadow = true;
rearSight.receiveShadow = true;
gun.add(rearSight);
// ----- Pistol Grip -----
const gripGeometry = new THREE.BoxGeometry(0.3, 0.5, 0.2);
const gripMaterial = new THREE.MeshStandardMaterial({ color: 0x222222 });
const grip = new THREE.Mesh(gripGeometry, gripMaterial);
grip.position.set(0.3, -0.3, -0.5);
grip.castShadow = true;
grip.receiveShadow = true;
gun.add(grip);
// Position the gun in front of the camera
gun.position.set(0.5, -1, -2); // Initial standing position
camera.add(gun); // Add the gun to the camera's hierarchy
// Enable shadows for gun parts
receiver.castShadow = true;
receiver.receiveShadow = true;
barrel.castShadow = true;
barrel.receiveShadow = true;
handguard.castShadow = true;
handguard.receiveShadow = true;
magazine.castShadow = true;
magazine.receiveShadow = true;
stock.castShadow = true;
stock.receiveShadow = true;
frontSight.castShadow = true;
frontSight.receiveShadow = true;
rearSight.castShadow = true;
rearSight.receiveShadow = true;
grip.castShadow = true;
grip.receiveShadow = true;
// ---------- Recoil Animation ----------
let isRecoiling = false;
const recoilDistance = 0.1; // How much the gun moves back
const originalGunPosition = gun.position.clone();
const originalGunRotationX = gun.rotation.x;
const recoilAnim = () => {
if (!isRecoiling) {
isRecoiling = true;
// Start recoil tween
new TWEEN.Tween(gun.position)
.to({ z: originalGunPosition.z - recoilDistance, y: originalGunPosition.y + 0.5 }, 100)
.easing(TWEEN.Easing.Linear.None)
.onComplete(() => {
// Start recovery tween
new TWEEN.Tween(gun.position)
.to({ z: originalGunPosition.z, y: originalGunPosition.y }, 100)
.easing(TWEEN.Easing.Linear.None)
.onComplete(() => {
isRecoiling = false;
})
.start();
})
.start();
// Optional: Add rotation recoil
new TWEEN.Tween(gun.rotation)
.to({ x: originalGunRotationX + 0.05 }, 100)
.easing(TWEEN.Easing.Linear.None)
.onComplete(() => {
new TWEEN.Tween(gun.rotation)
.to({ x: originalGunRotationX }, 100)
.easing(TWEEN.Easing.Linear.None)
.start();
})
.start();
}
};
// ---------- Collision Detection Setup ----------
const collidableObjects = [];
// Helper function to compute and store bounding boxes
function addCollidable(object) {
object.updateMatrixWorld(true); // Ensure the world's matrix is updated
const box = new THREE.Box3().setFromObject(object);
collidableObjects.push(box);
}
// Add collidable objects: trees, house, targets
trees.forEach(tree => addCollidable(tree));
addCollidable(house);
targets.forEach(target => addCollidable(target));
// ---------- Raycaster for Collision Detection ----------
const raycaster = new THREE.Raycaster();
// ---------- Animation Loop ----------
const clock = new THREE.Clock();
function animate(time) {
requestAnimationFrame(animate);
let deltaTime = clock.getDelta();
// Update TWEEN animations
TWEEN.update(time);
// ---------- Handle Running ----------
currentSpeed = (move.run && !isCrouching) ? runSpeed : walkSpeed;
// ---------- Update Velocity Based on Movement ----------
velocity.x -= velocity.x * 10.0 * deltaTime;
velocity.z -= velocity.z * 10.0 * deltaTime;
direction.z = Number(move.forward) - Number(move.backward);
direction.x = Number(move.right) - Number(move.left);
direction.normalize(); // this ensures consistent movements in all directions
if (move.forward || move.backward) velocity.z -= direction.z * currentSpeed * deltaTime;
if (move.left || move.right) velocity.x -= direction.x * currentSpeed * deltaTime;
// Timer for shooting
shootTimer -= deltaTime;
// ---------- Calculate Tentative Position ----------
const pos = controls.getObject().position.clone();
const tentativePos = pos.clone();
tentativePos.x -= velocity.x * deltaTime;
tentativePos.z -= velocity.z * deltaTime;
// ---------- Collision Detection ----------
const playerSphere = new THREE.Sphere(tentativePos, playerRadius - 0.5); // Buffer reduced to 0.5
let collision = false;
for (let i = 0; i < collidableObjects.length; i++) {
if (playerSphere.intersectsBox(collidableObjects[i])) {
collision = true;
break;
}
}
if (!collision) {
controls.getObject().position.copy(tentativePos);
} else {
// Attempt to move along X only
const tentativePosX = pos.clone();
tentativePosX.x -= velocity.x * deltaTime;
const playerSphereX = new THREE.Sphere(tentativePosX, playerRadius - 0.5);
let collisionX = false;
for (let i = 0; i < collidableObjects.length; i++) {
if (playerSphereX.intersectsBox(collidableObjects[i])) {
collisionX = true;
break;
}
}
if (!collisionX) {
controls.getObject().position.x -= velocity.x * deltaTime;
} else {
velocity.x = 0;
}
// Attempt to move along Z only
const tentativePosZ = pos.clone();
tentativePosZ.z -= velocity.z * deltaTime;
const playerSphereZ = new THREE.Sphere(tentativePosZ, playerRadius - 0.5);
let collisionZ = false;
for (let i = 0; i < collidableObjects.length; i++) {
if (playerSphereZ.intersectsBox(collidableObjects[i])) {
collisionZ = true;
break;
}
}
if (!collisionZ) {
controls.getObject().position.z -= velocity.z * deltaTime;
} else {
velocity.z = 0;
}
}
// ---------- Handle Jumping and Gravity ----------
if (!isOnGround) {
verticalVelocity -= gravity * deltaTime; // Apply gravity correctly (subtracting)
const newY = controls.getObject().position.y + verticalVelocity * deltaTime;
if (newY <= standingHeight) {
controls.getObject().position.y = standingHeight;
isOnGround = true;
verticalVelocity = 0;
} else {
controls.getObject().position.y = newY;
}
} else {
// Ensure player is on the ground
if (controls.getObject().position.y < standingHeight) {
controls.getObject().position.y = standingHeight;
}
}
// Prevent camera from going below crouch height if crouching
if (isCrouching && controls.getObject().position.y < crouchHeight) {
controls.getObject().position.y = crouchHeight;
}
// ---------- Handle Continuous Shooting ----------
if (isShooting && shootTimer <= 0) {
shoot();
shootTimer = shootInterval;
recoilAnim(); // Trigger recoil on shooting
}
// ---------- Update Bullets ----------
for (let i = 0; i < bullets.length; i++) {
const bullet = bullets[i];
// Move bullet based on its velocity and deltaTime
const velocityDelta = bullet.velocity.clone().multiplyScalar(deltaTime);
bullet.position.add(velocityDelta);
// Collision Detection with Targets
for (let j = 0; j < targets.length; j++) {
const target = targets[j];
const distance = bullet.position.distanceTo(target.position);
if (distance < 10) { // Assuming target radius ~10
// Remove target and bullet
scene.remove(target);
targets.splice(j, 1);
collidableObjects.splice(j, 1); // Remove from collidables
scene.remove(bullet);
bullets.splice(i, 1);
i--;
break;
}
}
// Remove bullets that are too far away
const distanceFromCamera = bullet.position.distanceTo(controls.getObject().position);
if (distanceFromCamera > 1000) {
scene.remove(bullet);
bullets.splice(i, 1);
i--;
}
}
renderer.render(scene, camera);
}
animate(performance.now());
// ---------- Remove Collision Visualization (Green Wireframe Sphere) ----------
// The following code was responsible for displaying the green wireframe sphere.
// Since it's no longer needed, it has been removed/commented out.
/*
// Collision Visualization Helpers
const sphereGeometry = new THREE.SphereGeometry(playerRadius, 16, 16);
const sphereMaterial = new THREE.MeshBasicMaterial({
color: 0x00ff00,
wireframe: true
});
const sphereHelper = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphereHelper.position.copy(controls.getObject().position);
scene.add(sphereHelper);
*/
</script>
</body>
</html>
Explanation of Changes:
Removed the Green Wireframe Sphere:
The sphereHelper was used to visualize the player's collision boundary. Since you no longer need this visual aid, the entire block of code responsible for creating and adding the sphere to the scene has been commented out at the end of the script.
javascript
// ---------- Remove Collision Visualization (Green Wireframe Sphere) ----------
// The following code was responsible for displaying the green wireframe sphere.
// Since it's no longer needed, it has been removed/commented out.
/*
// Collision Visualization Helpers
const sphereGeometry = new THREE.SphereGeometry(playerRadius, 16, 16);
const sphereMaterial = new THREE.MeshBasicMaterial({
color: 0x00ff00,
wireframe: true
});
const sphereHelper = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphereHelper.position.copy(controls.getObject().position);
scene.add(sphereHelper);
*/
Enhanced Collision Detection:
The collision detection has been refined to check the player's intended new position before applying movement. This ensures that collisions are handled more smoothly and prevents the player from getting stuck when moving backward or in other directions.
Combined Collision Check: Before moving the player, we create a playerSphere at the tentative new position and check for intersections with any collidable objects.
Separate Axis Collision Check: If a collision is detected at the combined position, we attempt to move along the X and Z axes separately. This allows the player to slide along walls or objects instead of getting completely stuck.
Buffer Adjustment: The buffer around the player's collision sphere has been slightly reduced to 0.5 to prevent the player from being too close to objects, which can cause sticking.
javascript
Final Notes:
Testing: After implementing these changes, test the game thoroughly to ensure that the collision detection works smoothly in all directions, especially when moving backward or interacting with complex objects.
Further Enhancements: For even more robust collision detection, consider using more advanced techniques like bounding volumes (e.g., Capsules) or physics libraries that handle collisions and responses more efficiently.
Performance Considerations: While the current collision detection method works for a moderate number of objects, optimizing the collision checks (e.g., spatial partitioning) can improve performance for larger scenes.
By following these modifications, the green wireframe sphere around the player will be removed, and the collision mechanics should be enhanced to prevent the player from getting stuck when moving backward or interacting with other objects.
// ---------- Calculate Tentative Position ----------
const pos = controls.getObject().position.clone();
const tentativePos = pos.clone();
tentativePos.x -= velocity.x * deltaTime;
tentativePos.z -= velocity.z * deltaTime;
// ---------- Collision Detection ----------
const playerSphere = new THREE.Sphere(tentativePos, playerRadius - 0.5); // Buffer reduced to 0.5
let collision = false;
for (let i = 0; i < collidableObjects.length; i++) {
if (playerSphere.intersectsBox(collidableObjects[i])) {
collision = true;
break;
}
}
if (!collision) {
controls.getObject().position.copy(tentativePos);
} else {
// Attempt to move along X only
const tentativePosX = pos.clone();
tentativePosX.x -= velocity.x * deltaTime;
const playerSphereX = new THREE.Sphere(tentativePosX, playerRadius - 0.5);
let collisionX = false;
for (let i = 0; i < collidableObjects.length; i++) {
if (playerSphereX.intersectsBox(collidableObjects[i])) {
collisionX = true;
break;
}
}
if (!collisionX) {
controls.getObject().position.x -= velocity.x * deltaTime;
} else {
velocity.x = 0;
}
// Attempt to move along Z only
const tentativePosZ = pos.clone();
tentativePosZ.z -= velocity.z * deltaTime;
const playerSphereZ = new THREE.Sphere(tentativePosZ, playerRadius - 0.5);
let collisionZ = false;
for (let i = 0; i < collidableObjects.length; i++) {
if (playerSphereZ.intersectsBox(collidableObjects[i])) {
collisionZ = true;
break;
}
}
if (!collisionZ) {
controls.getObject().position.z -= velocity.z * deltaTime;
} else {
velocity.z = 0;
}
}
This method ensures that the player can still move along one axis even if there's a collision on the other, preventing the player from getting entirely stuck when moving backward or sideways.
Additional Improvements:
Player Sphere Radius Adjustment: The collision sphere's radius has been fine-tuned to playerRadius - 0.5 to provide a buffer that prevents the player from getting too close to collidable objects.
Code Cleanup: Removed unnecessary comments and ensured consistent formatting for better readability.