HTML部分:
<head>
<meta charset="UTF-8">
<title></title>
<style>
#fly{
position: absolute;
top: 50px;;left: 100px;height: 100px;width:100px;
border: 1px solid red;
}
#blooditem,#blood{position: absolute;
left: 80px;top: 10px ;width: 7px;height: 80px;border: 1px solid red;}
#blood{background-color: red;top: 0px;height: 80px;left: 0px;width:5px;left: 0px;}
#plane{width: 50px;height: 50px;border: 1px solid #ccc;position: absolute;top: 600px;left: 600px;}
#screen{border:1px solid #ccc;height: 700px;width: 1000px;position: absolute;top: 0px;left: 0px;box-sizing: border-box;}
.bullet{position: absolute;width:16px;height: 16px;border-radius: 50%;background-color: red;}
</style>
</head>
<body>
<div id="screen">
<div id="fly">Boss
<div id="blooditem">
<div id="blood"></div>
</div>
</div>
<div id="plane">我是飞机</div>
</div>
<script type="text/javascript" src="../js/new_file.js">
</script>
</body>
JS部分:
;(function(){
var obj=function(){
var div;
var body;
var plane;
var blood;
var flag=false;
var player=function(){
var left;
if(div.currentStyle){
//IE浏览器
left.div.currentStyle.left;
}else{
//谷歌浏览器
left=getComputedStyle(div,null).left;
}
//把100px转为100数值
left=parseInt(left);
//如果层跑到最右边则让flag=true;
if(left>=900){
flag=true;
}
//如果层跑到最左边则让flag=flase;
if(left<=100){
flag=false;
}
//console.log(getComputedStyle(div,null).left);
//div.style.left=left+100+"px";
setTimeout(function(){
if(flag){
div.style.left=left-1+"px";
}else{
div.style.left=left+1+"px";
}
player();
},10);
}
var planeMove=function(event){
plane.style.top=event.y-25+"px";
plane.style.left=event.x-25+"px";
}
//碰撞系统函数
var hitSystem=function(but){
//找出Boss的位置范围
var bosspos=getComputedStyle(div,null);
//判断子弹是否处于boss位置
if(
(
parseInt(but.style.left)>parseInt(bosspos.left)
&&
parseInt(but.style.left)<
(parseInt(bosspos.left)+parseInt(bosspos.width))
)
&&
(
parseInt(but.style.top)>parseInt(bosspos.top)
&&
parseInt(but.style.top)<
(parseInt(bosspos.top)+parseInt(bosspos.height))
)
){
//alert("被打中");
//让子弹消失
body.removeChild(but);
//掉血
var bloodcss=getComputedStyle(blood,null);
blood.style.top=parseInt(bloodcss.top)+8+"px";
blood.style.height=parseInt(bloodcss.height)-8+"px";
}
}
var bulletFly=function(but){
if(parseInt(but.style.top)>-16){
setTimeout(function(){
but.style.top=parseInt(but.style.top)-10+"px";
hitSystem(but);
bulletFly(but);
},50)
}
}
var hit=function(event){
if(event.keyCode==32){
//创建1个子弹
var bullet=document.createElement("div");
bullet.setAttribute("class","bullet");
//挂在到页面上
body.appendChild(bullet);
//挂完以后改变子弹位置在小飞机的头部
var flypos=getComputedStyle(plane,null);
bullet.style.left=parseInt(flypos.left)+17+"px";
bullet.style.top=parseInt(flypos.top)-16+"px";
//让子弹飞
bulletFly(bullet);
}
}
var loadEvent=function(){
body.planeMove;
document.body.hit;
}
return{
init:function(){
div=document.getElementById("fly");
body=document.getElementById("screen");
plane=document.getElementById("plane");
blood=document.getElementById("blood");
//直接执行
player();
//绑定事件
loadEvent();
}
}
}();
obj.init();
})();