$(() => {
let plane = $('.plane')
let container = $('.container')
let maxLeft = container.innerWidth() - plane.innerWidth() //飞机最大left距离
let maxTop = container.innerHeight() - plane.innerHeight() //飞机最大top距离
$(window).keydown(({ keyCode }) => {
let top = plane.position().top
let left = plane.position().left
switch (keyCode) {
case 87: // W
top -= 10
break;
case 83: // S
top += 10
break;
case 65: // A
left -= 10
break;
case 68: // D
left += 10
break;
case 74: // J
shoot()
break;
}
// 给飞机限制区域
if (top < 0) top = 0 // 飞机不超过盒子上边
if (left < 0) left = 0 // 飞机不超过盒子左边
if (top > maxTop) top = maxTop // 飞机不超过盒子下边
if (left > maxLeft) left = maxLeft // 飞机不超过盒子右边
plane.css({ top, left })
})
// 子弹定位
let endTime = new Date()
function shoot() {
let bullet = $('<div/>').addClass('bullet')
container.append(bullet)
bullet.css({
// 飞机top距离-子弹自身高度
top: plane.position().top - bullet.innerHeight(),
// 飞机left + 飞机宽度一半 - 子弹宽度一半 = 子弹居中飞机中间
left: plane.position().left + plane.innerWidth() /2 - bullet.innerWidth() /2
})
}
// 子弹向上走
setInterval(() => {
$('.bullet').each(function () {
let bullet = $(this)
bullet.css({
top: bullet.position().top - 10
})
// 如果子弹top<0,子弹消除
if (bullet.position().top < 0)
bullet.remove()
})
$('.enemy').each(function () {
let enemy = $(this)
enemy.css({
top: enemy.position().top + 10,
})
// 如果敌机top>盒子高度,敌机消除
if (enemy.position().top > container.innerHeight())
enemy.remove()
})
}, 100);
//不间断生成敌机
setInterval(() => {
let enemy = $('<div/>').addClass('enemy')
container.append(enemy)
enemy.css({
top: 0,
left: Math.random() * (container.innerWidth() - enemy.innerWidth())
})
}, 2000);
function getPostion(node) {
return {
l: node.offsetLeft,
t: node.offsetTop,
r: node.offsetLeft + node.offsetWidth,
b: node.offsetTop + node.offsetHeight
}
}
function calcCollision(a, b) {
a = getPostion(a)
b = getPostion(b)
if (a.l > b.l && a.l < b.r && a.t > b.t && a.t < b.b) return true
if (a.l > b.l && a.l < b.r && a.b > b.t && a.b < b.b) return true
if (a.r > b.l && a.r < b.r && a.b > b.t && a.b < b.b) return true
if (a.r > b.l && a.r < b.r && a.t > b.t && a.t < b.b) return true
return false
}
//不间断检测碰撞
setInterval(() => {
let me = plane.get(0)
$('.enemy').each(function (i, enemy) {
if (calcCollision(me, enemy) || calcCollision(enemy, me)) {
alert("GG")
location.reload()
}
$('.bullet').each(function (j, bullet) {
if (calcCollision(bullet, enemy) || calcCollision(enemy, bullet)) {
bullet.remove()
enemy.remove()
}
})
})
}, 50);
})