本文介绍如何使用JavaScript实现一个简易的坦克移动小游戏。核心功能包括通过CSS transform属性实现坦克图片的旋转,以及监听键盘上下左右键(键值37-40)控制坦克在指定容器内的移动与边界检测。
JavaScript坦克移动游戏实现
本文分享了使用JavaScript实现坦克移动小游戏的完整代码,供读者参考学习。
首先介绍如何实现图片的旋转功能,这是坦克转向的基础。
var current = 180;//需要反转的角度
tank.style.transform = 'rotate('+current+'deg)';//在style里的transform赋值'rotate('+current+'deg)'
以下是简易坦克移动小游戏的实现代码。注意:键盘上下左右方向键对应的键值分别为37、38、39和40。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id='container'>
<img src="tank.png" alt="" id='tank'>
</div>
</body>
<script>
container.style="width:1000px;height:800px;border:3px solid;";
tank.style="width:200px;height:200px;position:relative;top:0px;left:0px;"
document.body.onkeydown=function(){
var current = 0;
var top = parseInt(tank.style.top);
var left = parseInt(tank.style.left);
var code = event.keyCode;
if(code == 37) {
current = 180;
tank.style.transform = 'rotate('+current+'deg)';
if(left <= 0) {
alert("您已经到最左边了!");
}
else{
tank.style.left = (left-10) +"px";
}
}
if(code == 38) {
current =270;
tank.style.transform = 'rotate('+current+'deg)';
if(top <= 0) {
alert("您已经到最上边了!");
}
else{
tank.style.top = (top-10) +"px";
}
}
if(code == 39) {
current = 0;
tank.style.transform = 'rotate('+current+'deg)';
if(left+parseInt(tank.width)+6 >= 1000) {
alert("您已经到最右边了!");
}
else{
tank.style.left = (left+10) +"px";
}
}
if(code == 40) {
current = 90;
tank.style.transform = 'rotate('+current+'deg)';
if(top+parseInt(tank.width)+6 >= 800) {
alert("您已经到最下边了!");
}
else{
tank.style.top = (top+10) +"px";
}
}
}
</script>
</html>

以上就是本文的全部内容,希望能为读者的学习提供帮助,欢迎大家继续支持本站。