Html飞机大战(七):发射第一颗子弹
好家伙,终于到子弹了
我们先来理一理思路:
子弹由飞机射出,所以我们把发射子弹的方法写在英雄类中
当然了,子弹也必须有自己独立的类
后期会有很多子弹射出,所以一个个将子弹类实例化肯定是不对的
我们也需要一个弹夹(一个数组)去装子弹(子弹对象)
我们先把第一个子弹渲染到飞机的头上
开搞:
1.子弹的配置项和类编辑
//子弹配置项
const BULLET = {
img: b,
width: 9,
height: 21,
}
//子弹类编辑
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() {}
paint(context) {
console.log(this.img, this.x, this.y)
context.drawImage(this.img, this.x, this.y)
}
}
2.补充图片的src
const b = new Image();
b.src = "img/bullet.jpg"
网上偷图,妙啊
3.我们为Hero类添加新的方法
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();
console.log(currentTime - this.lastShootTime);
if (currentTime - this.lastShootTime > this.shootInterval) {
//初始化一个子弹对象
console.log("测试shoot");
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;
}
}
}
3.1.属性说明
//子弹上次射击的时间
this.lastShootTime = new Date().getTime();
//子弹射击的间隔
this.shootInterval = 200;
//子弹夹数组
this.bulletList = [];
lastShootTime时间用于判断子弹更新的时机
shootInterval用于控制子弹刷新的间隔
bulletList后面的多次渲染子弹会用到
3.2.方法说明
shoot() {
//获取当前的时间
const currentTime = new Date().getTime();
console.log(currentTime - this.lastShootTime);
if (currentTime - this.lastShootTime > this.shootInterval) {
//初始化一个子弹对象
console.log("测试shoot");
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;
}
}
同样的用控制时间差的原理来保证刷新速率
还是那条公式:当前时间 - 创建实例时的时间 > 我规定的时间间隔
子弹的绘制,想想怎么把它渲染在飞机的正上方
BULLET, this.x + this.width / 2 - BULLET.width / 2 + 2, this.y - BULLET.height / 2
x,y是渲染飞机的坐标
横坐标:x加上一般的飞机宽度再减去一半的子弹宽度
纵坐标:y减去一般的子弹高度
(canvas的纵坐标是向下的哟)
(最后再调整一下,加一加二之类的)
ok,来看看效果
gif录不到,但确实是有的
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具