JavaScript仿微信打飞机游戏(2)

var main = document.getElementById('main'); var my = document.getElementById('my'); var score = document.getElementById("score"); var context = my.getContext('2d'); var crashId; var fallCount = 0; //记录没被打中的飞机数,如果超过10,游戏结束 var aligh = 0 ; var count = 0; //记录打中的飞机数,即当前得分 var leftArr = []; var arrPic = []; var left; var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img,aligh,100); } //生成自己,且可以左右移动 function move(event){ event = EventUtil.getEvent(event); context.clearRect(aligh,100,47,47); if(event.keyCode == 39 && aligh < 260 ){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, aligh,100); } aligh += 10 ; } if (aligh == 260){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, 260,100); } } } document.onkeypress = move; //随机生成敌机 (function(){ var createId = setInterval(function(){ var top = 0+'px'; var enemy = document.createElement("img"); enemy.src = "../images/enemy.png"; var randomleft = Math.floor(Math.random() * 300) ; left = randomleft > 260 ? 260 + 'px': randomleft + 'px'; leftArr.push(left); //保存每个敌机的距左边的距离,方便碰撞检测的计算 arrPic.push(enemy); //将每个敌机的图片保存在数组中,方便碰撞检测后移除 main.appendChild(enemy); enemy.style.paddingLeft = left ; enemy.style.paddingTop = top; var spandom = $("#main>img:last-child");//找到最后一个span spandom.animate({"paddingTop":420},6000,function(){ //移除元素 this.remove(); arrPic.splice(0,1); //移除图片 leftArr.splice(0,1); //从数组中移除距离 fallCount ++; }); //如果落下的飞机数超过十个没有被打中,则游戏结束 if(fallCount >= 10){ clearInterval(createId); clearInterval(crashId); alert("当前得分 :"+count+" , 很遗憾,游戏结束!") } },1000); })(); //碰撞检测 function checkCrash(){ crashId = setInterval(function(){ for(var i = 0; i < leftArr.length; i++) { var tempL = parseInt(leftArr[i]); var tempA = parseInt(aligh); if(tempL <= (tempA + 20) && (tempA + 20) <= (tempL + 40)){ arrPic[i].remove(); //碰撞检测,移除敌机的图片 count++; score.innerHTML = "当前得分 "+count; continue; } } console.log(count); },2200); } checkCrash(); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyspxg.html