I have other code to go with this, but whenever a bullet despawns (hits the edge or times out), the player gets damaged. I haven’t been able to test if the player gets damaged when they collide because of how much damage is done passively.
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’ve tried a few options with conditions in the if statement. None worked. The decreasePlayerHealth function should only run when the bullet hits the player.