To resolve the issue where the player slightly penetrates the box colliders and gets stuck, we'll enhance the collision detection mechanism. The current implementation uses raycasting to detect collisions, which might not be sufficient for preventing slight penetrations, especially when moving diagonally or at high speeds.
Instead, we'll utilize the circleIntersectsBox2D function you've already defined. This function checks if a circular area (representing the player's collision boundary) intersects with any rectangular box colliders in the X-Z plane. By integrating this function into the movement logic, we can ensure that the player stops before reaching the collider, thus preventing any penetration.
Here's a step-by-step guide to implementing this improvement:
Remove or Modify Raycasting Collision Detection:
The existing raycasting approach can be replaced with the circleIntersectsBox2D function for more accurate collision detection.
Integrate circleIntersectsBox2D into Movement Logic:
Before applying movement, check if the new position would result in a collision. If a collision is detected, prevent the movement or adjust it to stop just before the collider.
Adjust Collision Buffer:
Ensure that the collisionBuffer is sufficiently large to prevent penetration but not too large to cause unintended movement restrictions.
Update Collision Detection in the Animation Loop:
Modify the animate function to incorporate the new collision detection logic.
Below is the updated code incorporating these changes:
html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>First-Person Shooter Game with Enhanced Collision Detection</title>
<style>
/* [Existing CSS styles remain unchanged] */
</style>
<!-- Import Map remains unchanged -->
<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">
Нажмите для игры<br>
W/A/S/D для движения | Мышь для обзора | Клик для стрельбы<br>
Пробел для прыжка | Ctrl для приседания | Shift для бега
</div>
<!-- Scope Overlay remains unchanged -->
<div id="scope">
<!-- [Scope HTML remains unchanged] -->
</div>
<script type="module">
'use strict';
// [Imports and initial setup remain unchanged]
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';
// Constants for player height and collider radius
const standingHeight = 10.0;
const crouchHeight = 7.0;
const playerRadius = 1.5; // Player collision radius
const collisionBuffer = 0.5; // Buffer to stop before collision
// [Scene, camera, renderer setup remains unchanged]
const scene = new THREE.Scene();
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);
// [Lighting, sun, clouds, ground, trees, targets, house setup remain unchanged]
// [Omitting unchanged code for brevity]
// ---------- Collision Detection Setup ----------
const collidableObjects = [];
// Function to add an object to the collidable list
function addCollidable(object) {
const box = new THREE.Box3().setFromObject(object);
collidableObjects.push(box);
}
// Adding colliders: trees, house, targets
trees.forEach(tree => addCollidable(tree));
addCollidable(house);
targets.forEach(target => addCollidable(target));
// ---------- Toggle Bounding Boxes Visibility (for debugging) ----------
// [Debug helpers code remains unchanged]
// ---------- 2D Collision Detection Function ----------
function circleIntersectsBox2D(x, z, radius, box) {
// Find the closest point on the box to the circle's center
const closestX = Math.max(box.min.x, Math.min(x, box.max.x));
const closestZ = Math.max(box.min.z, Math.min(z, box.max.z));
// Calculate the squared distance between the circle's center and this closest point
const distanceSq = (x - closestX) ** 2 + (z - closestZ) ** 2;
return distanceSq < (radius * radius);
}
// ---------- Initialization of 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 position
controls.getObject().position.y = standingHeight;
// ---------- Movement Variables ----------
const move = {
forward: false,
backward: false,
left: false,
right: false,
run: false
};
let speed = 200.0; // Base speed (units per second)
const runMultiplier = 1.75; // Speed multiplier for running
// ---------- Jump and Gravity Variables ----------
const gravity = 2000.0; // Gravity force (units per second squared)
let isOnGround = true;
let verticalVelocity = 0.0;
// ---------- Crouching Variables ----------
let isCrouching = false;
// ---------- Shooting Variables ----------
let isShooting = false; // Flag for continuous shooting
const fireRate = 10; // Fire rate (bullets per second)
const shootInterval = 1 / fireRate; // Interval between shots
let shootTimer = 0; // Timer to track shooting
// ---------- Event Handlers 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
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;
// 'Control' keyup is not handled to allow toggle on key press
}
};
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
// ---------- Event Handlers for Mouse Shooting ----------
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);
// ---------- Crouching Functionality ----------
function toggleCrouch() {
if (isCrouching) {
// Stand up
isCrouching = false;
// Smoothly return camera to standing position
new TWEEN.Tween(controls.getObject().position)
.to({ y: standingHeight }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
// Smoothly return gun position to standing
new TWEEN.Tween(gun.position)
.to({ y: -1 }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
} else {
// Crouch down
isCrouching = true;
// Smoothly lower camera to crouch position
new TWEEN.Tween(controls.getObject().position)
.to({ y: crouchHeight }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
// Smoothly lower gun to crouch position
new TWEEN.Tween(gun.position)
.to({ y: -1.5 }, 200)
.easing(TWEEN.Easing.Linear.None)
.start();
}
}
// ---------- Bullets Array ----------
const bullets = [];
const bulletSpeed = 1000; // Bullet speed (units per second)
const bulletGeometry = new THREE.SphereGeometry(0.5, 8, 8);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 }); // Yellow bullet
// ---------- Shooting Mechanic ----------
const shoot = () => {
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
bullet.position.copy(controls.getObject().position);
bullet.position.y -= 1; // Adjust bullet 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 Model Setup ----------
const gun = new THREE.Group();
// [Gun parts setup remains unchanged]
// [Omitting unchanged code for brevity]
// Positioning the gun in front of the camera
gun.position.set(0.5, -1, -2); // Initial standing position
camera.add(gun); // Add gun to the camera's hierarchy
// Enable shadows for gun parts
// [Enabling shadows remains unchanged]
// ---------- Gun Recoil Animation ----------
let isRecoiling = false;
const recoilDistance = 0.1; // Recoil distance
const originalGunPosition = gun.position.clone();
const originalGunRotationX = gun.rotation.x;
const recoilAnim = () => {
if (!isRecoiling) {
isRecoiling = true;
// Recoil forward
new TWEEN.Tween(gun.position)
.to({ z: originalGunPosition.z - recoilDistance, y: originalGunPosition.y + 0.5 }, 100)
.easing(TWEEN.Easing.Linear.None)
.onComplete(() => {
// Return to original position
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 rotational 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();
}
};
// ---------- Main Animation Loop ----------
const clockObj = new THREE.Clock();
function animate(time) {
requestAnimationFrame(animate);
let deltaTime = clockObj.getDelta();
// Update TWEEN animations
TWEEN.update(time);
// ---------- Handle Running ----------
let currentSpeed = speed;
if (move.run && !isCrouching) {
currentSpeed *= runMultiplier; // Increase speed when running
}
// ---------- Calculate Movement ----------
let moveX = 0;
let moveZ = 0;
if (move.forward) moveZ += 1;
if (move.backward) moveZ -= 1;
if (move.left) moveX -= 1;
if (move.right) moveX += 1;
// Normalize movement to prevent faster diagonal movement
const movementDirection = new THREE.Vector3(moveX, 0, moveZ).normalize();
if (movementDirection.length() === 0) {
// No movement
movementDirection.set(0, 0, 0);
}
const movement = movementDirection.multiplyScalar(currentSpeed * deltaTime);
// ---------- Calculate Tentative New Position ----------
const pos = controls.getObject().position.clone();
const tentativeX = pos.x + movement.x;
const tentativeZ = pos.z + movement.z;
// ---------- Collision Detection ----------
let collision = false;
for (let box of collidableObjects) {
if (circleIntersectsBox2D(tentativeX, tentativeZ, playerRadius + collisionBuffer, box)) {
collision = true;
break;
}
}
if (!collision) {
// Apply movement if no collision detected
controls.moveRight(movement.x);
controls.moveForward(movement.z);
} else {
// Attempt to move only along X axis
let collisionX = false;
for (let box of collidableObjects) {
if (circleIntersectsBox2D(tentativeX, pos.z, playerRadius + collisionBuffer, box)) {
collisionX = true;
break;
}
}
if (!collisionX) {
controls.moveRight(movement.x);
}
// Attempt to move only along Z axis
let collisionZ = false;
for (let box of collidableObjects) {
if (circleIntersectsBox2D(pos.x, tentativeZ, playerRadius + collisionBuffer, box)) {
collisionZ = true;
break;
}
}
if (!collisionZ) {
controls.moveForward(movement.z);
}
// If collision on both axes, do not move
}
// ---------- Handle Jumping and Gravity ----------
if (!isOnGround) {
verticalVelocity -= gravity * deltaTime; // Apply gravity
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 stays on the ground
if (controls.getObject().position.y < standingHeight) {
controls.getObject().position.y = standingHeight;
}
}
// Prevent camera from going below crouch height
if (isCrouching && controls.getObject().position.y < crouchHeight) {
controls.getObject().position.y = crouchHeight;
}
// ---------- Handle Continuous Shooting ----------
shootTimer -= deltaTime;
if (isShooting && shootTimer <= 0) {
shoot();
shootTimer = shootInterval;
recoilAnim(); // Trigger gun recoil
}
// ---------- 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);
// Check collision 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 from the scene and arrays
scene.remove(target);
targets.splice(j, 1);
collidableObjects.splice(j, 1); // Remove from colliders
scene.remove(bullet);
bullets.splice(i, 1);
i--;
break;
}
}
// Remove bullet if it travels too far
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());
</script>
</body>
</html>
Explanation of Changes:
Collision Detection Integration:
Removed Raycasting: The existing raycasting collision detection using THREE.Raycaster has been removed to prevent discrepancies between ray intersections and actual player collisions.
Used circleIntersectsBox2D: This function checks if the player's circular collision boundary intersects with any box colliders in the X-Z plane.
Movement Logic Enhancement:
Tentative Position Calculation: Before applying movement, the code calculates the tentative new position (tentativeX, tentativeZ) based on the desired movement vector.
Collision Checking: For each collider in collidableObjects, the circleIntersectsBox2D function checks if moving to the tentative position would result in a collision. If a collision is detected, movement is either prevented or adjusted to allow movement along one axis if possible.
Per-Axis Collision Handling: If a diagonal movement results in a collision, the code attempts to allow movement along the X and Z axes independently, preventing the entire movement only if both axes are obstructed.
Adjustments to Collision Buffer:
Buffer Size: The collisionBuffer is set to 0.5, ensuring that the player stops before coming too close to the collider. You can adjust this value based on the desired proximity to the colliders.
Ensured Accurate Box Colliders:
Box3s in collidableObjects: Each collidable object (trees, house, targets) is represented as a THREE.Box3 and stored in the collidableObjects array for collision checks.
Smooth Movement Adjustments:
Selective Axis Movement: When a collision is detected in one axis (e.g., X), the player can still move along the other axis (e.g., Z), providing smoother navigation around obstacles.
Maintained Other Functionalities:
Jumping, Crouching, Shooting: All other game mechanics such as jumping, crouching, and shooting remain unchanged and function as intended.
Additional Recommendations:
Performance Optimization:
Bounding Volume Hierarchy (BVH): For larger scenes with many colliders, implementing a spatial partitioning system like BVH can optimize collision detection performance.
Visual Feedback:
Collision Indicators: You can visualize collision boundaries or provide feedback when the player is near a collider to enhance user experience.
Further Collision Precision:
3D Collision Detection: Currently, collision is checked only in the X-Z plane. For more precise collision handling, especially with varying heights of colliders, consider implementing 3D collision detection.
Testing and Tuning:
Adjust Collision Buffer: Depending on the specific game mechanics and player speed, you might need to tweak the collisionBuffer to achieve the best balance between accessibility and collision prevention.
By integrating the circleIntersectsBox2D function into the movement logic, the player will now stop before reaching any collider, effectively preventing any penetration and ensuring a smoother gameplay experience.