js文件和网页做如下修改。支持飞机发出多颗子弹。
学生可以改下,增加在屏幕上面运动的长方形,代表敌机。
然后增加敌机和子弹的碰撞检测。
function Czidan(){
this.x = 245;
this.y = 400;
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 ;
//this.x = this.x + this.sudu * Math.sin(this.jiaodu);
if (this.y < 10)
this.stop=1;
//if (this.y == 10)
//this.jiaodu = Math.atan((x - this.x) / (y - this.y));
}
}
}
<!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 c = 0;
var zidans = new Array(100);
zidans[c] = new Czidan();
//zidans[c].stop = 0;
$(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);
for (var i = 0; i <c; i++) {
ctx.beginPath();
ctx.arc(zidans[i].x, zidans[i].y, 10, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//动画的逻辑,子弹直线运动,超出范围,则重新设置为10
zidans[i].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)
{
c = c + 1;
//alert(c);
zidans[c] = new Czidan();
zidans[c].stop = 0;
}
});
</script>
</html>
4993

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



