<head>
<script language = "javascript" type = "text/javascript">
function MyTank(x,y,direct){
//tank的坐标和方向
this.x = x;
this.y = y;
this.direct = direct;
this.speed = 5;
//初始化tank
mytank.style.left = this.x + "px";
mytank.style.top = this.y + "px";
mytank.style.backgroundPositionY = "0px";
this.move = function move(event){
//a表示左 3
//s表示下 2
//d表示右 1
//w表示上 0
switch(event.keyCode){
case 65:
//a表示左 3
this.x -= this.speed;
this.direct = 3;
mytank.style.backgroundPositionY = "40px";
break;
case 83:
//s表示下 2
this.y += this.speed;
this.direct = 2;
mytank.style.backgroundPositionY = "80px";
break;
case 68:
//d表示右 1
this.x += this.speed;
this.direct = 1;
mytank.style.backgroundPositionY = "120px";
break;
case 87:
//w表示上 0
this.y -= this.speed;
this.direct = 0;
mytank.style.backgroundPositionY = "0px";
break;
}
//改变tank的位置
mytank.style.left = this.x + "px";
mytank.style.top = this.y + "px";
}
}
</script>
</head>
<body onkeydown = "dosth(event)">
<div id = "filed" style = "background-color:black;width:500px;height:400px;position:absolute">
<div id = "mytank" style = "background-position-y: 0px;background-image:url('tank.png');
width:40px;height:40px;left:10px;top:10px;position:absolute"></div>
</div>
<script language = "javascript" type = "text/javascript">
//创建坦克对象
var hero = new MyTank(200,360,0);
//判断用户希望做什么操作的方法
function dosth(event){
if(event.keyCode == 65 ||event.keyCode == 68 ||event.keyCode == 83||event.keyCode == 87){
hero.move(event);
}
//下面可以写调用发射子弹的方法。。
}
</script>
</body>
素材:
本文介绍了一个使用JavaScript实现的简单坦克游戏,包括坦克的移动、键盘事件监听和基本的游戏逻辑。
18

被折叠的 条评论
为什么被折叠?



