The issue you're encountering stems from the collision detection mechanism allowing the player to slightly penetrate the collider boundaries. This penetration can cause the player to get stuck inside objects. To resolve this, we'll make a few key adjustments to your collision detection logic:
-
Ensure Correct Reference to Collidable Objects:
- The current implementation stores
THREE.Box3 instances in the collidableObjects array. However, the Raycaster expects THREE.Object3D instances (like Mesh objects) for intersection tests. This mismatch prevents accurate collision detection.
-
Adjust the Collision Buffer:
- The
collisionBuffer determines how close the player can get to an object before being stopped. Increasing this value can help prevent the player from penetrating the collider.
-
Incorporate Player's Collision Radius:
- To ensure the player stops before their collider intersects with an object, incorporate the player's radius into the collision checks.
-
Refine Movement Adjustment Upon Collision:
- Instead of moving the player by
(distance - collisionBuffer), adjust their position based on their radius and the collision buffer to ensure a smooth stop before collision.
Let's implement these changes step-by-step.
1. Store Object3D References Instead of Box3 Instances
Modify the addCollidable function to store references to the actual objects (THREE.Object3D) instead of their bounding boxes. This allows the Raycaster to properly detect intersections.
// Change collidableObjects to store Object3D instances
const collidableObjects = [];
// Update the addCollidable function
function addCollidable(object) {
collidableObjects.push(object);
}
Explanation:
- By storing the
Object3D instances, the Raycaster can effectively perform intersection tests with these objects.
2. Update Collision Buffer
Increase the collisionBuffer to include the player's radius. This ensures the player stops before their collider intersects with objects.
// Update collision buffer to include player's radius
const collisionBuffer = playerRadius + 0.5; // Player radius + additional buffer
Explanation:
- This adjustment ensures the player maintains a safe distance from collidable objects, preventing any overlap.
3. Refine Collision Detection Logic
Adjust the collision detection to consider the player's radius and ensure the player stops before any collision occurs.
// ---------- Обнаружение столкновений и предотвращение проникновения ----------
function handleCollisions(pos, movement, deltaTime) {
// Create a sphere representing the player's current position and radius
const playerSphere = new THREE.Sphere(new THREE.Vector3(pos.x, pos.y, pos.z), playerRadius);
// Iterate through all collidable objects to check for intersections
for (let obj of collidableObjects) {
const box = new THREE.Box3().setFromObject(obj);
// Check for collision using the player's sphere and object's bounding box
if (playerSphere.intersectsBox(box)) {
// Determine the direction of movement and adjust accordingly
// Here, we'll prevent movement by resetting movement vectors
return true; // Collision detected
}
}
return false; // No collision
}
Explanation:
- This function creates a spherical collider for the player and checks for intersections with all collidable objects.
- If a collision is detected, it returns
true, indicating that movement should be restricted.
4. Integrate Collision Handling into Movement Logic
Incorporate the collision handling into your movement logic to prevent the player from moving into collidable objects.
// In the animate function, replace existing collision logic with the new handler
function animate(time) {
requestAnimationFrame(animate);
let deltaTime = clockObj.getDelta();
// Update TWEEN animations
TWEEN.update(time);
// Determine current speed
let currentSpeed = speed;
if (move.run && !isCrouching) {
currentSpeed *= runMultiplier;
}
// Calculate movement direction
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 direction
const movementDirection = new THREE.Vector3(moveX, 0, moveZ).normalize();
if (movementDirection.length() === 0) {
movementDirection.set(0, 0, 0);
}
// Calculate movement distance
const movement = movementDirection.multiplyScalar(currentSpeed * deltaTime);
// Calculate tentative new position
const pos = controls.getObject().position.clone();
const tentativePos = pos.clone().add(new THREE.Vector3(movement.x, 0, movement.z));
// Handle collisions
if (!handleCollisions(tentativePos, movement, deltaTime)) {
// No collision, proceed with movement
controls.moveRight(movement.x);
controls.moveForward(movement.z);
} else {
// Collision detected, prevent movement
// Optionally, you can allow sliding along surfaces by modifying movement vectors
}
// ---------- Handle Jumping and Gravity (unchanged) ----------
// ... existing gravity and jumping code ...
// ---------- Handle Shooting and Bullet Updates (unchanged) ----------
// ... existing shooting code ...
renderer.render(scene, camera);
}
Explanation:
- Before applying movement, calculate the player's tentative new position.
- Use the
handleCollisions function to check if this position would result in a collision.
- If no collision is detected, apply the movement. Otherwise, prevent the movement.
- This ensures the player cannot move into collidable objects, effectively stopping them before collision.
5. Optional: Smooth Sliding Along Surfaces
To enhance the experience, you can allow the player to slide along surfaces when colliding rather than coming to a complete stop. Here's how you can modify the collision handling to enable sliding:
function handleCollisions(pos, movement, deltaTime) {
const playerSphere = new THREE.Sphere(new THREE.Vector3(pos.x, pos.y, pos.z), playerRadius);
let collisionDetected = false;
for (let obj of collidableObjects) {
const box = new THREE.Box3().setFromObject(obj);
if (playerSphere.intersectsBox(box)) {
collisionDetected = true;
// Calculate the penetration depth and direction
const penetrationVector = new THREE.Vector3();
box.clampPoint(playerSphere.center, penetrationVector);
penetrationVector.sub(playerSphere.center);
// Project movement onto the penetration vector
const dot = movement.dot(penetrationVector.normalize());
if (dot < 0) {
const adjustedMovement = movement.clone().sub(penetrationVector.clone().multiplyScalar(dot));
controls.moveRight(adjustedMovement.x);
controls.moveForward(adjustedMovement.z);
}
}
}
return collisionDetected;
}
Explanation:
- This adjustment calculates the penetration vector and adjusts the player's movement to allow sliding along the object's surface instead of a complete stop.
- This provides a smoother experience when navigating around objects.
6. Remove Debug Helpers (If Not Needed)
If you have visualization helpers for the bounding boxes and they are causing confusion or performance issues, consider removing or disabling them in the production environment.
// Remove or disable debugHelpers if not needed
const debugHelpers = new THREE.Group();
scene.add(debugHelpers);
// Toggle visibility with 'B'
window.addEventListener('keydown', (event) => {
if (event.code === 'KeyB') {
debugHelpers.visible = !debugHelpers.visible;
}
});
7. Final Adjustments and Testing
After implementing these changes:
-
Test Movement:
- Move the player towards various objects to ensure they stop before collision boundaries.
- Verify that the buffer is sufficient to prevent any penetration.
-
Adjust Buffer and Radius if Needed:
- If you notice slight penetrations or excessive stopping, fine-tune the
collisionBuffer value.
-
Optimize Performance:
- Ensure that collision checks are efficient, especially if you have many collidable objects.
-
Handle Edge Cases:
- Test scenarios like moving diagonally into corners to ensure consistent behavior.
By implementing these changes, your collision detection should prevent the player from penetrating collider boundaries, thereby eliminating the issue of getting stuck within objects. This approach ensures a smoother and more reliable movement experience in your game.