<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>First-Person…
- User
- Assistant
The issue you're encountering with collision detection for the red cubes likely stems from the current collision detection method using
THREE.Raycaster. While raycasting is efficient for certain scenarios, it can miss collisions, especially with large objects or when approaching from multiple angles. To ensure robust and reliable collision detection with all sides of your red cubes (targets), I recommend switching to Sphere-Box Collision Detection. This method involves treating the player as a sphere and the red cubes as boxes, allowing for more accurate and comprehensive collision checks.Why Sphere-Box Collision Detection?
- Comprehensive Collision Coverage: Unlike raycasting, which checks along specific directions, sphere-box collision detection evaluates the entire volume around the player, ensuring that collisions are detected from any direction.
- Simplicity and Efficiency: Implementing sphere-box collisions can be straightforward and performant, especially for a limited number of objects.
Step-by-Step Guide to Implement Sphere-Box Collision Detection
1. Define the Player's Bounding Sphere
First, represent the player as a sphere using
THREE.Sphere. This sphere will be used to detect collisions with the bounding boxes of the red cubes.// Define the player's bounding sphere const playerBoundingSphere = new THREE.Sphere(); playerBoundingSphere.radius = playerRadius; // 1.5 as defined earlier2. Update the Bounding Sphere Position
Before processing movement, update the sphere's position to the player's intended new position.
/** * Updates the player's bounding sphere position based on the controls. */ function updatePlayerBoundingSphere(newPosition) { playerBoundingSphere.center.copy(newPosition); }3. Create Bounding Boxes for Collidable Objects
Ensure that each collidable object (trees, walls, red cubes) has an updated bounding box.
// Create and store bounding boxes for all collidable objects const collidableBoundingBoxes = collidableObjects.map(obj => { const box = new THREE.Box3().setFromObject(obj); return box; });4. Implement the Collision Detection Function
Create a function that checks whether the player's bounding sphere intersects with any of the collidable objects' bounding boxes.
/** * Checks if the player's bounding sphere intersects with any collidable bounding boxes. * @returns {boolean} - Returns true if a collision is detected, else false. */ function checkSphereBoxCollisions() { for (let box of collidableBoundingBoxes) { if (playerBoundingSphere.intersectsBox(box)) { return true; } } return false; }5. Integrate Collision Detection into the Movement Logic
Modify the movement logic to incorporate the new collision detection method. Before actually moving the player, simulate the new position and check for collisions.
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; } // Determine 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 intended movement const intendedMovement = movementDirection.multiplyScalar(currentSpeed * deltaTime); // Simulate new position const simulatedPosition = controls.getObject().position.clone().add(intendedMovement); playerBoundingSphere.center.copy(simulatedPosition); // Check for collisions let collisionDetected = false; for (let box of collidableBoundingBoxes) { if (playerBoundingSphere.intersectsBox(box)) { collisionDetected = true; break; } } if (!collisionDetected) { // No collision; apply movement controls.moveRight(intendedMovement.x); controls.moveForward(intendedMovement.z); } else { // Collision detected; handle accordingly // You can implement more nuanced responses here (e.g., sliding along walls) } // Handle gravity and jumping (unchanged) if (!isOnGround) { verticalVelocity -= gravity * deltaTime; 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 { if (controls.getObject().position.y < standingHeight) { controls.getObject().position.y = standingHeight; } } if (isCrouching && controls.getObject().position.y < crouchHeight) { controls.getObject().position.y = crouchHeight; } // Handle shooting and bullets (unchanged) shootTimer -= deltaTime; if (isShooting && shootTimer <= 0) { shoot(); shootTimer = shootInterval; recoilAnim(); } // Update bullets (unchanged) for (let i = 0; i < bullets.length; i++) { const bullet = bullets[i]; const velocityDelta = bullet.velocity.clone().multiplyScalar(deltaTime); bullet.position.add(velocityDelta); // Check collision with targets (unchanged) for (let j = 0; j < targets.length; j++) { const target = targets[j]; const distance = bullet.position.distanceTo(target.position); if (distance < 10) { // Radius of target scene.remove(target); targets.splice(j, 1); collidableObjects.splice(collidableObjects.indexOf(target), 1); collidableBoundingBoxes.splice(j, 1); // Remove corresponding bounding box scene.remove(bullet); bullets.splice(i, 1); i--; break; } } // Remove bullets that are too far (unchanged) const distanceFromCamera = bullet.position.distanceTo(controls.getObject().position); if (distanceFromCamera > 1000) { scene.remove(bullet); bullets.splice(i, 1); i--; } } // Update bounding boxes in case any objects have moved or been removed visualizeBoundingBoxes(); renderer.render(scene, camera); }6. Update Bounding Boxes When Objects Move or Are Removed
Ensure that the bounding boxes are updated whenever objects are moved or removed from the scene.
/** * Updates the bounding boxes for all collidable objects. */ function updateBoundingBoxes() { collidableBoundingBoxes.length = 0; // Clear existing boxes collidableObjects.forEach(obj => { const box = new THREE.Box3().setFromObject(obj); collidableBoundingBoxes.push(box); }); } // Call this function whenever you add or remove collidable objects7. Remove Raycaster-Based Collision Detection
Since we're switching to sphere-box collision detection, you can remove or comment out the existing
Raycaster-based collision detection to prevent conflicts.// Remove or comment out these lines: // const raycaster = new THREE.Raycaster(); // const collisionDirection = new THREE.Vector3(); // ... and any related Raycaster logic.8. Optional: Implement Sliding Along Walls
The current implementation simply prevents movement if a collision is detected. For a smoother experience, consider implementing sliding along walls by checking each axis separately.
if (!collisionDetected) { controls.moveRight(intendedMovement.x); controls.moveForward(intendedMovement.z); } else { // Try moving only along X const tentativePositionX = controls.getObject().position.clone().add(new THREE.Vector3(intendedMovement.x, 0, 0)); playerBoundingSphere.center.copy(tentativePositionX); let collisionX = false; for (let box of collidableBoundingBoxes) { if (playerBoundingSphere.intersectsBox(box)) { collisionX = true; break; } } if (!collisionX) { controls.moveRight(intendedMovement.x); } // Reset sphere center to original position playerBoundingSphere.center.copy(controls.getObject().position); // Try moving only along Z const tentativePositionZ = controls.getObject().position.clone().add(new THREE.Vector3(0, 0, intendedMovement.z)); playerBoundingSphere.center.copy(tentativePositionZ); let collisionZ = false; for (let box of collidableBoundingBoxes) { if (playerBoundingSphere.intersectsBox(box)) { collisionZ = true; break; } } if (!collisionZ) { controls.moveForward(intendedMovement.z); } // Reset sphere center to original position playerBoundingSphere.center.copy(controls.getObject().position); }9. Update Bounding Boxes Visualization
Ensure that the bounding boxes are visualized correctly for debugging purposes. You may need to update the visualization to reflect the new bounding boxes.
function visualizeBoundingBoxes() { debugHelpers.clear(); // Clear previous helpers collidableBoundingBoxes.forEach(box => { const boxHelper = new THREE.Box3Helper(box, 0x00ff00); debugHelpers.add(boxHelper); }); }10. Ensure Bounding Boxes are Accurate for Red Cubes
Double-check that each red cube is correctly added to the
collidableObjectsarray and that their bounding boxes are accurately calculated.// When creating red cubes (targets), ensure they are fully added 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); collidableObjects.push(box); // Ensure they are added to collidableObjects // Optionally, update bounding boxes immediately const boxBounding = new THREE.Box3().setFromObject(box); collidableBoundingBoxes.push(boxBounding); }Final Thoughts
By implementing sphere-box collision detection, you ensure that the player cannot pass through red cubes from any direction, providing a more reliable and immersive experience. This method accounts for collisions comprehensively around the player's position, eliminating the gaps where the raycasting approach might fail.
Additionally, consider the following enhancements for even better collision handling:
- Dynamic Bounding Boxes: If any collidable objects move during gameplay, ensure their bounding boxes are updated accordingly.
- Performance Optimization: For larger numbers of collidable objects, consider spatial partitioning techniques (like Octrees) to optimize collision checks.
- Physics Integration: For more advanced collision responses (like sliding or bouncing), integrating a physics engine (e.g., Cannon.js or Ammo.js) might be beneficial.
Implementing these changes should resolve the collision detection issues with your red cubes, ensuring that the player cannot move through them from any side.