I've encountered a problem with my code where bullets causing damage to the player even after despawning or hitting an edge. It's difficult to troubleshoot since the damage is applied passively, making it challenging to isolate specific collisions.
function shootPlayer() {
if (!document.body.contains(enemy)) return; // Stop if the enemy is removed
const playerRect = player.getBoundingClientRect();
const playerCenterX = playerRect.left + playerRect.width / 2;
const playerCenterY = playerRect.top + playerRect.height / 2;
const enemyRect = enemy.getBoundingClientRect();
const enemyCenterX = enemyRect.left + enemyRect.width / 2;
const enemyCenterY = enemyRect.top + enemyRect.height / 2;
const angle = Math.atan2(playerCenterY - enemyCenterY, playerCenterX - enemyCenterX);
const bullet = document.createElement('div');
bullet.className = 'bullet';
bullet.style.position = 'absolute';
bullet.style.top = `${enemyCenterY}px`;
bullet.style.left = `${enemyCenterX}px`;
document.body.appendChild(bullet);
const bulletSpeed = 5;
const bulletDamage = 5;
function moveBullet() {
let bulletTop = parseFloat(bullet.style.top);
let bulletLeft = parseFloat(bullet.style.left);
bulletTop += bulletSpeed * Math.sin(angle);
bulletLeft += bulletSpeed * Math.cos(angle);
bullet.style.top = `${bulletTop}px`;
bullet.style.left = `${bulletLeft}px`;
console.log(`Bullet Position: (${bulletLeft}, ${bulletTop})`);
// Simple collision detection with the player
if (
bulletLeft >= playerRect.left &&
bulletLeft <= playerRect.right &&
bulletTop >= playerRect.top &&
bulletTop <= playerRect.bottom
) {
decreasePlayerHealth(bulletDamage);
bullet.remove();
console.log('Bullet hit the player.');
return;
}
// Check if the bullet is out of bounds and remove it
if (bulletTop < 0 || bulletTop > window.innerHeight || bulletLeft < 0 || bulletLeft > window.innerWidth) {
bullet.remove();
console.log('Bullet despawned.');
return;
}
// Continue moving the bullet
requestAnimationFrame(moveBullet);
}
requestAnimationFrame(moveBullet);
}
I have attempted various solutions within the if statement conditions without success. The decreasePlayerHealth function should only execute when the bullet successfully strikes the player.