首先我们把上个例子中的代码进行修改。把子弹封装成一个类。写在一个单独的js文件中,然后在网页中引用这个类。
封装成一个类,便于我们更好的重复使用这段代码,关于类和对象的概念,大家可以google下。
代码如下Czidan.js: 对照上一个代码,看看是哪些代码给移过来了。然后保证网页的效果没有改变。
这是一种代码的组织方式,代码多的时候,我们希望把它分到多个文件,便于维护。
这里例子大家可以做一下修改:
1.把子弹发出的位置和停止的位置改成正确的。
2.子弹停止的时候,让他复位到发出的位置。
3.把子弹和飞机碰撞的代码移到Czidan.js文件中,给Czidan添加一个碰撞检测的方法。
function Czidan(){
this.x = 245;
this.y = 10;
this.jiaodu = Math.PI * 0.5;
this.sudu = 10;
this.dadao = 0;//0代表没打到,1代表打到
this.move = function () {
this.y = this.y + this.sudu * Math.cos(this.jiaodu);
this.x = this.x + this.sudu * Math.sin(this.jiaodu);
if (this.y > 500)
this.y = 10;
//if (this.y == 10)
this.jiaodu = Math.atan((x - this.x) / (450 - this.y));
}
}
另外我们在网页文件中添加了两句代码
var zidans = new Array(100);
zidans[0]=new Czidan();
原来的zidan变成了zidans。这里有一个数组的概念,自己google下。
其实,飞机也可以放到这个数组里面,这个概念,我们后面再说。
下面,我们改一下,改成子弹是由飞机打出来的。
于是,我们修改了Czidan.js文件,如下。现在你已经有点感觉到分成多个文件写的好处了吧。
function Czidan(){
this.x = 245;
this.y = 10;
this.jiaodu = Math.PI * 0.5;
this.sudu = 10;
this.dadao = 0;//0代表没打到,1代表打到
this.stop = 1;
this.move = function () {
if (this.stop == 1)
{ }
else
{
this.y = this.y + this.sudu * Math.cos(this.jiaodu);
this.x = this.x + this.sudu * Math.sin(this.jiaodu);
if (this.y > 500)
this.y = 10;
//if (this.y == 10)
this.jiaodu = Math.atan((x - this.x) / (450 - this.y));
}
}
}
经过这个修改,子弹默然是不动的,按了空格键后才会动起来。
html文件的代码如下;
<!DOCTYPE html>
<html>
<head>
<title>多颗子弹</title>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript" src="Czidan.js"></script>
<script type="text/javascript">
var x = 225;
var mousex, mousey;
var canvas;
var ctx;
var zidans = new Array(100);
zidans[0]=new Czidan();
$(document).ready(function () {
canvas = $(document).get(0).getElementById("MyCanvas");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
animate();
}
});
function animate()
{
ctx.clearRect(0, 0, 500, 500);
//由键盘控制的方块
if (zidans[0].dadao == 1)
ctx.fillStyle = "red";
ctx.fillRect(x, 450, 50, 50);
ctx.beginPath();
ctx.arc(zidans[0].x, zidans[0].y, 10, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//动画的逻辑,子弹直线运动,超出范围,则重新设置为10
zidans[0].move();
//碰撞检测,如果打到,则方块变成红色,游戏停止
if((zidans[0].y>450)&&(zidans[0].y<500))
{
zidans[0].dadao = 1;
}
setTimeout(animate, 100);
};
</script>
</head>
<body >
<div>
<canvas id="MyCanvas" width="500" height="500" > </canvas>
</div>
</body>
<script type="text/javascript">
//注意这里是document,canvas应该也能捕获keydown事件,留以后试吧
$(document).keydown(function (e) {
var k = e.keyCode;
//如果不知道按键的代码,用alert输出看
//alert(k);
if (k == 37)
x = x - 5;
if (k == 39)
x = x + 5;
if (k == 32)
{
zidans[0].stop = 0;
}
});
</script>
</html>
本文介绍如何将游戏中的子弹行为封装为类,提高代码组织性和维护性。通过将子弹行为从代码中分离出来,我们能够更容易地修改和扩展游戏逻辑,特别是涉及到子弹的发射、移动和碰撞检测等功能。同时,通过使用数组来存储多个实例,我们可以方便地管理多个子弹对象,从而实现在游戏中的多颗子弹同时存在和交互。此外,文章还展示了如何使子弹在按空格键后开始移动,增加了游戏的互动性和趣味性。
4993

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



