The issue you're experiencing with collision detection—where the player can pass through objects instead of stopping just before them—is primarily due to how the collision detection function checkCollision is implemented and how it's being called within your movement logic. Let's dive into the problem and provide a comprehensive solution to enhance collision detection in your game.
Understanding the Problem
1. Collision Detection Logic:
Your current checkCollision function uses a single Raycaster to detect collisions either along the X or Z axis based on the magnitude of dir and distance. However, in your movement logic, you're passing both dir and distance as the same value (tentativeMoveX or tentativeMoveZ). This causes the function to always prefer one axis over the other, leading to incorrect collision detection.
2. Axis Misalignment:
When moving along the X axis, the function mistakenly sometimes checks for collisions along the Z axis and vice versa, depending on the values. This misalignment results in inconsistent collision responses, allowing the player to move through objects.
Proposed Solution
To resolve these issues, we'll refactor the checkCollision function to separately handle collisions along the X and Z axes. We'll also modify how this function is called within the movement logic to ensure accurate collision detection.
Step 1: Refactor the checkCollision Function
We'll redefine the checkCollision function to accept specific parameters for the axis and direction of movement. This ensures that collisions are checked accurately along the intended axis.
javascript
/**
* Checks for collisions along a specific axis and direction.
* @param {string} axis - The axis to check ('x' or 'z').
* @param {number} direction - The direction of movement along the axis (+1 or -1).
* @param {number} distance - The intended movement distance.
* @returns {number} - The adjusted movement distance after collision detection.
*/
function checkCollision(axis, direction, distance) {
if (distance === 0) return 0;
// Set the collision direction based on the axis and direction
collisionDirection.set(
axis === 'x' ? direction : 0,
0,
axis === 'z' ? direction : 0
).normalize();
// Position the Raycaster at the player's current position
raycaster.set(controls.getObject().position, collisionDirection);
// Perform collision detection
const intersections = raycaster.intersectObjects(collidableObjects, true);
if (intersections.length > 0) {
const intersectionDistance = intersections[0].distance;
// Determine if the intersection is within the collision boundary
if (intersectionDistance < playerRadius + collisionBuffer + distance) {
// Calculate the maximum allowable movement to avoid collision
return Math.max(intersectionDistance - playerRadius - collisionBuffer, 0);
}
}
// No collision detected; allow full movement
return distance;
}
Step 2: Modify the Movement Logic to Utilize the Refactored Function
We'll adjust how checkCollision is called within the animate loop to specify the axis and direction explicitly:
javascript
// ---------- Главный цикл анимации ----------
function animate(time) {
requestAnimationFrame(animate);
let deltaTime = clockObj.getDelta();
// Обновление анимаций TWEEN
TWEEN.update(time);
// ---------- Обработка бега ----------
let currentSpeed = speed;
if (move.run && !isCrouching) {
currentSpeed *= runMultiplier; // Увеличение скорости при беге
}
// ---------- Расчёт перемещений ----------
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;
// Нормализация движения для предотвращения ускорения при диагональном движении
const movementDirection = new THREE.Vector3(moveX, 0, moveZ).normalize();
if (movementDirection.length() === 0) {
// Если нет движения, пропуск перемещения
movementDirection.set(0, 0, 0);
}
// Расчёт перемещения с учётом времени кадра
const movement = movementDirection.multiplyScalar(currentSpeed * deltaTime);
// ---------- Проверка столкновений при перемещении ----------
// Проверка и корректировка перемещения по X
const directionX = movement.x >= 0 ? 1 : -1;
const adjustedMoveX = checkCollision('x', directionX, Math.abs(movement.x));
controls.moveRight(adjustedMoveX * directionX);
// Проверка и корректировка перемещения по Z
const directionZ = movement.z >= 0 ? 1 : -1;
const adjustedMoveZ = checkCollision('z', directionZ, Math.abs(movement.z));
controls.moveForward(adjustedMoveZ * directionZ);
// ---------- Остальной код анимации ----------
// ... (прыжки, стрельба, обновление пуль и т.д.)
renderer.render(scene, camera);
}
animate(performance.now());
Step 3: Verify Collider Boundaries
Ensure that all objects intended to be collidable have proper bounding boxes or bounding spheres. If you're using custom geometries or complex models, consider adding invisible helper colliders or simplifying them to basic shapes for efficient collision detection.
Step 4: Optimize Collision Detection (Optional but Recommended)
For improved performance and more accurate collision handling, you might consider the following enhancements:
Use Bounding Boxes:
Compute and cache bounding boxes for all collidable objects to avoid recalculating them every frame.
Utilize THREE.Box3 for bounding box computations.
Spatial Partitioning:
Implement spatial partitioning (like a grid or quadtree) to reduce the number of collision checks per frame.
Physics Engine Integration:
Integrate a physics engine (e.g., Cannon.js, Ammo.js) for more robust collision handling, including responses like sliding along surfaces.
Complete Updated Code Snippet
Here's the updated portion of your script incorporating the above changes:
javascript
Additional Recommendations
1. Visualize Bounding Boxes for Debugging
It's beneficial to visualize bounding boxes to ensure that colliders are correctly positioned and sized. You already have a toggle for debug helpers. Ensure that these helpers accurately represent the colliders.
javascript
// Display bounding boxes for debugging
const debugHelpers = new THREE.Group();
scene.add(debugHelpers);
function visualizeBoundingBoxes() {
collidableObjects.forEach((obj) => {
const box = new THREE.Box3().setFromObject(obj);
const boxHelper = new THREE.Box3Helper(box, 0x00ff00);
debugHelpers.add(boxHelper);
});
}
visualizeBoundingBoxes();
// Toggle Bounding Boxes Visibility
window.addEventListener('keydown', (event) => {
if (event.code === 'KeyB') { // Нажмите 'B' для переключения
debugHelpers.visible = !debugHelpers.visible;
}
});
Tip: Make sure that the collidable objects have correctly sized and positioned bounding boxes. Misaligned or inaccurately sized bounding boxes can lead to improper collision detection.
2. Optimize Collidable Objects
Only include objects that should interact with the player in the collidableObjects array. Avoid adding unnecessary objects to reduce the number of collision checks and improve performance.
Ensure that each object in this array has a proper geometry that reflects its physical shape.
3. Consider Using a Physics Engine
For more advanced and efficient collision detection and response, integrating a physics engine like Cannon.js or Ammo.js can be highly beneficial. These engines handle complex physics interactions and can save you from implementing custom collision logic.
Example with Cannon.js:
javascript
// Initialize Cannon.js world
const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
// Create player body
const playerShape = new CANNON.Sphere(playerRadius);
const playerBody = new CANNON.Body({ mass: 1 });
playerBody.addShape(playerShape);
playerBody.position.set(0, standingHeight, 0);
world.addBody(playerBody);
// Sync Three.js camera with Cannon.js body
function syncCamera() {
camera.position.copy(playerBody.position);
}
Note: Integrating a physics engine requires significant changes to your existing code structure but offers more robust and scalable physics interactions.
Conclusion
By refactoring the collision detection function to handle each axis separately and ensuring that collisions are checked accurately along the intended directions, you can prevent the player from passing through objects. Additionally, visualizing bounding boxes and optimizing collidable objects can further enhance the reliability and performance of collision detection in your game.
Implementing these changes should resolve the issue of the player passing through objects and ensure that collisions are detected just before reaching object boundaries. If you continue to face issues, consider using a dedicated physics engine for more accurate and efficient collision handling.
Feel free to reach out if you need further assistance or clarifications!