<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
width: 100%;
height: 100%;
overflow: hidden;
user-select: none;
}
.self {
width: 120px;
height: auto;
position: absolute;
z-index: 9;
}
.bullet {
width: 30px;
height: 30px;
background-color: rgb(0, 255, 128);
clip-path: polygon(50% 0, 100% 40%, 100% 100%, 50% 60%, 0 100%, 0 40%);
position: absolute;
z-index: 1;
animation: bullet 1s linear forwards;
}
@keyframes bullet {
100% {
top: -10vh;
}
}
.enemy {
position: absolute;
z-index: 2;
top: -10vh;
animation: enemy 9s linear forwards;
}
@keyframes enemy {
100% {
top: 100vh;
}
}
</style>
</head>
<body>
<img src="img/self.png" class="self">
<script>
const self = document.querySelector('.self');
const body = document.body;
document.addEventListener('mousemove', function (e) {
// 使飞机跟随鼠标移动
self.style.top = e.clientY - self.offsetHeight / 2 + 'px';
self.style.left = e.clientX - self.offsetWidth / 2 + 'px';
});
// 创建子弹
function createBullet() {
const bullet = document.createElement('div');
bullet.classList.add('bullet');
bullet.style.top = self.offsetTop + self.clientHeight / 2 - bullet.clientHeight + 'px';
bullet.style.left = self.offsetLeft + self.clientWidth / 2 - bullet.clientWidth + 'px';
body.appendChild(bullet)
setTimeout(() => {
bullet.remove();
}, 2000);
}
setInterval(createBullet, 100);
// 获取随机数
function random(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 创建敌人
function enemy() {
const enemy = document.createElement('img');
enemy.setAttribute('src', `img/enemy${random(1,4)}.png`);
enemy.classList.add('enemy');
enemy.style.left = random(0, window.innerWidth - 100) + 'px'
body.appendChild(enemy)
}
setInterval(enemy, 300)
// 判断子弹与敌人是否发生碰撞
function ifCollision(el1, el2) {
let rect1 = el1.getBoundingClientRect();
let rect2 = el2.getBoundingClientRect();
return !(rect1.right < rect2.left || rect1.left > rect2.right || rect1.bottom < rect2.top || rect1.top >
rect2.bottom)
}
setInterval(() => {
let enemy = document.querySelectorAll('.enemy')
let bullet = document.querySelectorAll('.bullet')
enemy.forEach(enemy => {
bullet.forEach(bullet => {
if (ifCollision(enemy, bullet)) {
bullet.remove()
enemy.remove()
}
})
})
}, 100);
</script>
</body>
</html>