Html飞机大战(八):子弹的移动和管理

2022-11-03,,,,

好家伙,这应该是这个小游戏最难的几个点之一了

现在我们要做出子弹射击的效果我们应该如何处理?

1.首先我们要确定几个变量和方法的关系

变量: 子弹  bullet  弹夹(用来装子弹的东西)bulletList[] 

方法:装填子弹  绘制子弹 移动子弹

子弹发射的物理逻辑是很简单的:

生产第一个子弹,推入弹夹中,绘制弹夹(即绘制弹夹中的所有子弹),

生产第二个子弹,同样推入弹夹,移动第一颗子弹(应该说是改变第一颗子弹的y坐标),绘制弹夹中的所有子弹 

。。。。。。

。。。。。。

生产第n个子弹,推入弹夹中,改变第n-1颗子弹的Y坐标,绘制弹夹中的所有子弹

(这是本篇最重要的思路,这个不理清楚,做着做着就寄了,)

所以我们的思路就是:

(1)生产子弹,

(2)推入弹夹,

(3)移动子弹(只有第一次生产子弹是不用移动子弹的),

(4)绘制弹夹中的所有子弹  

思路理清,一切都通了

2.在类中添加方法

 class Hero {
constructor(config) {
this.width = config.width;
// this.height = config.heigth;
this.widthh = config.widthh;
this.x = (480 - config.width) / 2;
this.y = 650 - config.widthh;
// this.y = 650 - config.height;
this.frame = config.frame;
//用死/活来控制要渲染的图片组
this.img = null;
this.live = true;
//子弹上次设计的时间
this.lastShootTime = new Date().getTime();
//子弹射击的间隔
this.shootInterval = 200;
//子弹夹数组
this.bulletList = [];
}
judge() { } paint(context) {
this.img = this.frame.live[0];
context.drawImage(this.img, this.x, this.y, this.width, this.widthh);
}
//英雄的子弹设计间隔
shoot() {
//获取当前的时间
const currentTime = new Date().getTime(); if (currentTime - this.lastShootTime > this.shootInterval) {
//初始化一个子弹对象 let bullet = new Bullet(BULLET, this.x + this.width / 2 - BULLET.width / 2 + 2, this.y - BULLET
.height / 2);
this.bulletList.push(bullet);
//开始绘制子弹
//bullet.paint(context);
//更新时间
this.lastShootTime = currentTime;
} }
move() {
console.log("hero的move被触发");
this.y -= 2;
}
}

来到我们的Hero类

 let bullet = new Bullet(BULLET, this.x + this.width / 2 - BULLET.width / 2 + 2, this.y - BULLET
.height / 2);
this.bulletList.push(bullet);

很显然这两个就是

(1)“生产子弹”和(2)“推入弹夹”

随后是子弹类的编辑

class Bullet {
constructor(config, x, y) {
this.img = config.img;
this.width = config.width;
this.height = config.height;
this.x = x;
this.y = y;
}
//移动子弹
move() {
console.log("bullet的move被触发");
this.y -= 2;
}
//子弹绘制方法
paint(context) { context.drawImage(this.img, this.x, this.y)
}
}

这里就是

(3)移动子弹

(4)绘制弹夹中的所有子弹  

但是这显然不够完善

我们要操作的是整个弹夹

我们要用一个for循环去遍历弹夹中的每一个子弹并

(3)移动子弹

(4)绘制弹夹中的所有子弹  

3.添加全局变量

function judgeComponent() {
console.log("judge被触发");
for (let i = 0; i < hero.bulletList.length;i++) {
hero.bulletList[i].move();
}
}
//全局函数 来绘制所有的子弹/敌人组件
function paintComponent() {
for (let i = 0; i < hero.bulletList.length;i++) {
hero.bulletList[i].paint(context);
}
}

在状态中添加方法的使用

case RUNNING:
sky.judge();
sky.paint(context);
//加载主角 hero.paint(context);
hero.shoot();
judgeComponent();
paintComponent();
deleteComponent();
// context.drawImage(hero_frame.live[0], 0, 0);
break;

来看看效果:

 

搞定

(嗯,非常nice!)

Html飞机大战(八):子弹的移动和管理的相关教程结束。

《Html飞机大战(八):子弹的移动和管理.doc》

下载本文的Word格式文档,以方便收藏与打印。