Implement proximity-based hit detection
mainFor simple game mechanics where targets are relatively uniform, you can use a proximity-based hit test. This involves iterating through active projectiles (bullets) and checking the distance to visible targets using target.position.distanceTo(bullet.position).
If the distance is below a certain threshold (e.g., 1 unit), a hit is registered. Common actions upon a hit include:
- Removing the bullet from the scene.
- Hiding the target temporarily.
- Respawning the target at a new random position after a delay.
- Incrementing the score and updating the UI.
Note: For irregularly shaped objects or more precise requirements, use raycasting instead of proximity checks.
function onFrame() {
// ... unchanged params
Object.values(bullets).forEach((bullet) => {
// ... unchanged logic
targets
.filter((target) => target.visible)
.forEach((target) => {
const distance = target.position.distanceTo(bullet.position);
if (distance < 1) {
delete bullets[bullet.uuid];
scene.remove(bullet);
// make target disappear, and then reappear at a different place after 2 seconds
target.visible = false;
setTimeout(() => {
target.visible = true;
target.position.x = Math.random() * 10 - 5;
target.position.z = -Math.random() * 5 - 5;
}, 2000);
score += 10; // Update the score when a target is hit
updateScoreDisplay(); // Update the rendered troika-three-text object
}
});
});
}