CSY1018-assignment-2/scripts/enemy.js

64 lines
2.5 KiB
JavaScript
Raw Normal View History

2022-04-28 19:56:09 +00:00
/* enemy spawning logic */
var aliens = [];
var bombs = [];
2022-04-28 19:56:09 +00:00
2022-04-29 09:56:51 +00:00
/*Spawns Enemies*/
2022-04-28 19:56:09 +00:00
function spawnEnemy() {
var alien = document.createElement("div");
alien.className = "alien";
alien.id = "alien";
alien.style.zIndex = "2"
2022-04-28 19:56:09 +00:00
while (true) {
alien.style.left = Math.floor(Math.random() * document.body.offsetWidth) + "px";
if (document.elementFromPoint(alien.offsetLeft, alien.offsetTop).classList.contains("alien") == false) {
document.body.appendChild(alien);
alienLogic = setInterval(spawnBomb, 3000);
aliens.push([alien, alienLogic]);
2022-04-28 20:55:14 +00:00
console.log("Alien Spawned")
2022-04-28 19:56:09 +00:00
break;
}
}
}
2022-04-29 09:56:51 +00:00
/*Spawns a bomb*/
2022-04-28 19:56:09 +00:00
function spawnBomb() {
var alien = aliens[Math.floor(Math.random() * aliens.length)];
2022-04-28 19:56:09 +00:00
var bomb = document.createElement("div");
bomb.className = "bomb";
bomb.style.left = "28px";
bomb.style.top = "70px";
bomb.style.zIndex = "1";
bomb.style.display = "absolute";
alien[0].appendChild(bomb);
bombs.push(bomb);
2022-04-28 20:55:14 +00:00
console.log("Bomb Spawned")
2022-04-28 19:56:09 +00:00
}
2022-04-29 09:56:51 +00:00
/*Makes a random bomb fall a set amount and explodes if colliding with the floor*/
function fall() {
for (let element of bombs) {
element.style.top = (element.offsetTop + 10) + "px";
var closestElement = document.elementFromPoint(element.offsetLeft, element.offsetTop+10);
if (!closestElement.classList.contains("sky") && !closestElement.classList.contains("alien") && !closestElement.classList.contains("bomb") && !closestElement.classList.contains("explosion")) {
2022-04-29 11:10:37 +00:00
if(Math.floor(Math.random() * 100) < 10 || element.bottom >= document.body.bottom || closestElement.classList.contains("character")) {
element.className = "explosion";
console.log("Explosion")
setTimeout(() => {element.remove()}, 3000);
2022-04-28 20:55:14 +00:00
bombs.splice(bombs.indexOf(element),1);
console.log("Bomb Despawned");
}
}
}
}
2022-04-29 09:56:51 +00:00
/*Checks to see if player is colliding with exploded bomb*/
function checkExplosion() {
for (let element of document.getElementsByClassName("explosion")) {
var elemRect = element.getBoundingClientRect();
var playerRect = document.getElementById("player").getBoundingClientRect();
if (elemRect.bottom >= playerRect.top && elemRect.right >= playerRect.left && elemRect.left <= playerRect.right && elemRect.top-40 <= playerRect.bottom) {
document.getElementById("player").className = "character dead";
endGame();
}
}
}