<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>First-Person…
- User
- Assistant
The issue of the player getting stuck upon touching objects in your Three.js first-person shooter game likely stems from how the collision detection and movement handling are implemented. Here's a comprehensive guide to diagnosing and fixing the problem:
1. Understanding the Current Collision Detection
Your current implementation uses a 2D circle (
playerRadius) to represent the player's collision boundary and checks for intersections with the bounding boxes (Box3) of collidable objects. This method works in principle but can lead to issues if not carefully managed. Potential problems include:- Inaccurate Bounding Boxes: If the bounding boxes of objects are not tightly fitted, they can create larger collision areas than intended.
- Player Radius Too Large: A
playerRadiusthat's too large can cause frequent collisions, making the player feel stuck. - Movement Handling: Improper handling of movement vectors when a collision is detected can prevent smooth navigation around objects.
2. Step-by-Step Fixes
Let's address these potential issues systematically.
A. Visualize Collision Boundaries for Debugging
Before making changes, it's essential to visualize the collision boundaries to understand where the problem lies.
Add Debugging Helpers:
// Add this after defining the scene const debugHelpers = new THREE.Group(); scene.add(debugHelpers); // Function to visualize bounding boxes function visualizeBoundingBoxes() { collidableObjects.forEach(box => { const boxHelper = new THREE.Box3Helper(box, 0x00ff00); debugHelpers.add(boxHelper); }); } // Call this function after adding all collidable objects visualizeBoundingBoxes();Explanation:
- The
Box3Helperwill render green wireframes around all collidable objects, allowing you to see if the bounding boxes are appropriately sized.
Toggle Visibility: You can add a keyboard toggle to show/hide these helpers for convenience.
window.addEventListener('keydown', (event) => { if (event.code === 'KeyB') { // Press 'B' to toggle debugHelpers.visible = !debugHelpers.visible; } });B. Adjust Player Radius and Collision Buffer
A large
playerRadiusor a smallcollisionBuffercan cause the player to collide too easily.Suggested Adjustments:
const playerRadius = 1.5; // Reduced from 2.0 const collisionBuffer = 0.5; // Increased from 0.3Explanation:
- Reduced
playerRadius: Decreasing the player's collision radius allows for tighter movement around objects. - Increased
collisionBuffer: Providing a larger buffer ensures that the player doesn't get too close to objects, reducing the chance of getting stuck.
C. Refine Collision Detection Logic
Ensure that collision detection checks are accurate and efficient.
Update Collision Check Function:
function circleIntersectsBox2D(x, z, radius, box) { // Find the closest point on the box to the player's position 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 distance between the player's center and this closest point const distanceSq = (x - closestX) ** 2 + (z - closestZ) ** 2; return distanceSq < (radius * radius); }Ensure
collidableObjectsAre Accurate: Make sure that all static objects (trees, house, targets) have their bounding boxes correctly set.function addCollidable(object) { object.updateMatrixWorld(true); const box = new THREE.Box3().setFromObject(object); collidableObjects.push(box); }If objects are static, their bounding boxes don't need to be updated every frame. However, if objects move, ensure their bounding boxes are updated accordingly.
Periodic Update (If Needed):
If some objects can move, update their bounding boxes each frame.
function updateCollidableObjects() { collidableObjects.forEach((box, index) => { const object = collidableObjects[index].object; // Store a reference to the object box.setFromObject(object); }); }Call
updateCollidableObjects()inside your animation loop if objects move.D. Improve Movement Handling with Sliding
Current movement handling attempts to resolve collisions by allowing movement along individual axes if a diagonal movement causes a collision. However, this can be optimized for smoother sliding along surfaces.
Modify the Movement Logic:
// Inside your animate function, replace the collision handling section with the following: // Calculate intended movement direction const direction = new THREE.Vector3(); controls.getDirection(direction); direction.normalize(); // Create movement vectors 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 movement = new THREE.Vector3(moveX, 0, moveZ).normalize().multiplyScalar(currentSpeed * deltaTime); // Tentative new position const tentativePosition = controls.getObject().position.clone().add(movement); // Check collision at the new position let collision = false; for (let i = 0; i < collidableObjects.length; i++) { const box = collidableObjects[i]; if (circleIntersectsBox2D(tentativePosition.x, tentativePosition.z, playerRadius, box)) { collision = true; break; } } // If no collision, move if (!collision) { controls.moveRight(movement.x); controls.moveForward(movement.z); } else { // Try moving only along X const tentativeX = controls.getObject().position.x + movement.x; let collisionX = false; for (let i = 0; i < collidableObjects.length; i++) { const box = collidableObjects[i]; if (circleIntersectsBox2D(tentativeX, controls.getObject().position.z, playerRadius, box)) { collisionX = true; break; } } if (!collisionX) { controls.moveRight(movement.x); } // Try moving only along Z const tentativeZ = controls.getObject().position.z + movement.z; let collisionZ = false; for (let i = 0; i < collidableObjects.length; i++) { const box = collidableObjects[i]; if (circleIntersectsBox2D(controls.getObject().position.x, tentativeZ, playerRadius, box)) { collisionZ = true; break; } } if (!collisionZ) { controls.moveForward(movement.z); } }Explanation:
- Normalized Movement Vector: Ensures consistent movement speed in all directions.
- Tentative Position: Checks if moving in the intended direction causes a collision.
- Sliding: If a collision is detected, the code attempts to move along each axis separately, allowing the player to slide along obstacles instead of getting stuck.
E. Fine-Tune Player Height and Positioning
Ensure that the player's vertical position doesn't interfere with movement, especially during jumping and crouching.
Additional Checks:
// Ensure the player's Y position is correctly handled if (controls.getObject().position.y < crouchHeight) { controls.getObject().position.y = crouchHeight; }Explanation:
- Prevents the player from sinking below the crouch height, which could potentially interfere with collision detection or movement.
3. Additional Recommendations
A. Use Raycasters for Forward Collision Detection
Implementing raycasters can provide more precise collision detection, especially for forward movement.
Example Implementation:
const raycaster = new THREE.Raycaster(); const directionVector = new THREE.Vector3(); function checkForwardCollision(movement) { directionVector.copy(movement).normalize(); raycaster.set(controls.getObject().position, directionVector); const intersects = raycaster.intersectObjects(collidableObjects.map(box => box.object), true); if (intersects.length > 0) { const distance = intersects[0].distance; if (distance < playerRadius) { return true; } } return false; } // Use this function before moving forward if (!checkForwardCollision(movement)) { controls.moveForward(movement.z); }Explanation:
- Casts a ray in the direction of movement to detect potential collisions ahead of time.
- Prevents the player from moving into objects proactively.
B. Consider Using a Physics Engine
For more complex collision handling and physics interactions, integrating a physics engine like Cannon.js or Ammo.js can provide robust solutions.
Pros:
- Accurate collision detection and response.
- Handles complex interactions like slopes, bouncing, and more.
Cons:
- Adds complexity to your project.
- Requires learning the physics engine's API.
C. Optimize Performance
If you have many collidable objects, performance can degrade due to numerous collision checks each frame.
Optimization Tips:
- Spatial Partitioning: Implement techniques like spatial hashing or quad/octrees to reduce the number of collision checks.
- Layering: Categorize objects into layers (e.g., terrain, buildings, enemies) and prioritize collision checks based on relevance.
4. Final Revised Code Snippet
Here's how you can integrate some of the above suggestions into your existing code:
// Adjust playerRadius and collisionBuffer const playerRadius = 1.5; // Reduced from 2.0 const collisionBuffer = 0.5; // Increased from 0.3 // Visualization helpers (for debugging) const debugHelpers = new THREE.Group(); scene.add(debugHelpers); function visualizeBoundingBoxes() { collidableObjects.forEach(box => { const boxHelper = new THREE.Box3Helper(box, 0x00ff00); debugHelpers.add(boxHelper); }); } visualizeBoundingBoxes(); // Toggle bounding boxes visibility window.addEventListener('keydown', (event) => { if (event.code === 'KeyB') { // Press 'B' to toggle debugHelpers.visible = !debugHelpers.visible; } }); // Update collision handling in animate function function animate(time) { requestAnimationFrame(animate); let deltaTime = clockObj.getDelta(); // Update TWEEN animations TWEEN.update(time); // Handle running 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; const movement = new THREE.Vector3(moveX, 0, moveZ).normalize().multiplyScalar(currentSpeed * deltaTime); // Tentative new position const tentativePosition = controls.getObject().position.clone().add(movement); // Check for collision at tentative position let collision = false; for (let i = 0; i < collidableObjects.length; i++) { const box = collidableObjects[i]; if (circleIntersectsBox2D(tentativePosition.x, tentativePosition.z, playerRadius, box)) { collision = true; break; } } // Move accordingly if (!collision) { controls.moveRight(movement.x); controls.moveForward(movement.z); } else { // Try moving only along X const tentativeX = controls.getObject().position.x + movement.x; let collisionX = false; for (let i = 0; i < collidableObjects.length; i++) { const box = collidableObjects[i]; if (circleIntersectsBox2D(tentativeX, controls.getObject().position.z, playerRadius, box)) { collisionX = true; break; } } if (!collisionX) { controls.moveRight(movement.x); } // Try moving only along Z const tentativeZ = controls.getObject().position.z + movement.z; let collisionZ = false; for (let i = 0; i < collidableObjects.length; i++) { const box = collidableObjects[i]; if (circleIntersectsBox2D(controls.getObject().position.x, tentativeZ, playerRadius, box)) { collisionZ = true; break; } } if (!collisionZ) { controls.moveForward(movement.z); } } // Handle jumping and gravity 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; } } // Prevent sinking below crouch height if (isCrouching && controls.getObject().position.y < crouchHeight) { controls.getObject().position.y = crouchHeight; } // Handle shooting shootTimer -= deltaTime; if (isShooting && shootTimer <= 0) { shoot(); shootTimer = shootInterval; recoilAnim(); } // Update bullets 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 for (let j = 0; j < targets.length; j++) { const target = targets[j]; const distance = bullet.position.distanceTo(target.position); if (distance < 10) { // Target radius 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 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); }5. Summary
By implementing the above changes, you should experience smoother movement with reduced instances of getting stuck when the player interacts with objects in the game world. Here's what we've addressed:
- Visualization: Added helpers to visualize collision boundaries, aiding in debugging.
- Parameter Tuning: Adjusted
playerRadiusandcollisionBufferfor better collision responsiveness. - Collision Logic: Enhanced collision detection and movement handling to allow sliding along obstacles.
- Optional Enhancements: Suggested using raycasters and physics engines for more robust solutions.
6. Further Enhancements
For a more refined experience, consider the following:
- Slope Handling: Implement logic to handle slopes or uneven terrain if your game world requires it.
- Dynamic Objects: If you have moving objects, ensure their collision boundaries are updated each frame.
- Performance Optimization: Use spatial partitioning to limit collision checks to nearby objects, improving performance in large scenes.
Feel free to reach out if you encounter further issues or need more assistance with specific parts of your game!