web tank(1.1)

本文介绍了一个使用JavaScript实现的简单坦克游戏,包括坦克的移动、键盘事件监听和基本的游戏逻辑。
<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>

素材:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蟹道人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值