微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html双人飞机游戏代码

html双人飞机游戏代码

HTML双人飞机游戏代码

<html>
<head>
<title>双人飞机游戏</title>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>

<script>
//获取canvas元素
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");

//定义飞机类
function Plane(x,y,width,height,src){
    this.x=x;
    this.y=y;
    this.width=width;
    this.height=height;
    this.img=new Image();
    this.img.src=src;
    //绘制方法
    this.draw=function(){
        context.drawImage(this.img,this.x,this.y,this.width,this.height);
    }
}

//定义玩家1和玩家2的飞机
var player1=new Plane(350,500,80,"player1.png");
var player2=new Plane(350,20,"player2.png");

//定义子弹类
function Bullet(x,src,speed){
    this.x=x;
    this.y=y;
    this.width=width;
    this.height=height;
    this.img=new Image();
    this.img.src=src;
    this.speed=speed;
    //绘制子弹
    this.draw=function(){
        context.drawImage(this.img,this.height);
    }
    //更新子弹位置
    this.update=function(){
        this.y-=this.speed;
    }
}

//玩家1的子弹数组
var bullets1=[];
//玩家2的子弹数组
var bullets2=[];

//发射子弹方法
function fire(bullets,plane){
    var bullet=new Bullet(plane.x+plane.width/2-5,plane.y,10,"bullet.png",10);
    bullets.push(bullet);
}

//监听键盘事件
document.onkeydown=function(event){
    //玩家1的控制
    if(event.keyCode==37){
        player1.x-=10;
    }else if(event.keyCode==39){
        player1.x+=10;
    }else if(event.keyCode==38){
        fire(bullets1,player1);
    }
    //玩家2的控制
    if(event.keyCode==65){
        player2.x-=10;
    }else if(event.keyCode==68){
        player2.x+=10;
    }else if(event.keyCode==87){
        fire(bullets2,player2);
    }
}

//更新子弹位置
function updateBullets(bullets){
    for(var i=0;i<bullets.length;i++){
        bullets[i].update();
        bullets[i].draw();
        //子弹超出边界就从数组中删除
        if(bullets[i].y<0){
            bullets.splice(i,1);
            i--;
        }
    }
}

//游戏循环
setInterval(function(){
    //清空画布
    context.clearRect(0,canvas.width,canvas.height);
    //绘制玩家和子弹
    player1.draw();
    player2.draw();
    updateBullets(bullets1);
    updateBullets(bullets2);
},50);

</script>
</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐