头部信息
博客班级 |
https://edu.cnblogs.com/campus/zjcsxy/SE2020 |
小程序作业要求 |
|
作业源代码 |
https://github.com/1xu1/wechat_app |
学号 |
31801115 |
院系 |
浙大城市学院计算系 |
第一次接触微信小程序开发,所以就用了微信开发者工具创建小游戏项目创建出来的默认demo来练手,在观察学习的基础上添加了一些新的要素和特色。
(因为是第一次接触,所以难免会有些不足之处和不了解,望谅解)
我在此demo的基础上增添了玩家生命值系统,让敌机也有能力发射子弹,并使撞机的伤害比子弹更高,新增了新的回血掉落物以及切换三连发掉落物(拾取后玩家在一段时间内加快子弹发射速度,切换为三连发模式),掉落物刷新有自己的冷却时间,修改了飞机子弹刷新速率等等。
默认小程序创建步骤:
点击红框部分
点击新建
我们就可以得到一份原始demo
原始demo在网上已经有了分析博客,所以我就不在此赘述了,贴上网上找到的分析博客地址:
https://www.cnblogs.com/Phoenix-blog/p/10948630.html
目前我的项目的文件结构:
该demo中已经帮我们实现了游戏里最基础的sprite(精灵)以及简单的碰撞检测机制,因此我们可以在继承这个类的基础上做出很多游戏内的实体(如敌机,掉落物,子弹等等)
/** * 游戏基础的精灵类 */ export default class Sprite { constructor(imgSrc = '', width= 0, height = 0, x = 0, y = 0) { this.img = new Image() this.img.src = imgSrc this.width = width this.height = height this.x = x this.y = y this.visible = true } /** * 将精灵图绘制在canvas上 */ drawToCanvas(ctx) { if ( !this.visible ) return ctx.drawImage( this.img, this.x, this.y, this.width, this.height ) } /** * 简单的碰撞检测定义: * 另一个精灵的中心点处于本精灵所在的矩形内即可 * @param{Sprite} sp: Sptite的实例 */ isCollideWith(sp) { let spX = sp.x + sp.width / 2 let spY = sp.y + sp.height / 2 if ( !this.visible || !sp.visible ) return false return !!( spX >= this.x && spX <= this.x + this.width && spY >= this.y && spY <= this.y + this.height ) } }
为此我在databus.js文件中添加了更多的数据类型,以兼容我新增的几个实体(值得一提的是这个文件中的代码也实现了简单的对象池,以提高游戏运行效率,为此我也为回收新增的几个实体写了几个方法)
constructor() { if ( instance ) return instance instance = this this.hp_re = new Hp_re(20,0,2) this.shoot_mode3=new Shoot_mode3(20,0,2) this.pool = new Pool() this.reset() } reset() { this.frame = 0 this.score = 0 this.bullets = [] this.enemy_bullets=[] this.enemys = [] this.animations = [] this.gameOver = false }
通过修改增添index.js文件中的代码,我实现了玩家飞机的射击模式切换以及新的射击模式,未来可以在此添加更多的射击模式,以及增加了一个新的hp变量,来实现生命值系统。
shoot() { if(this.shoot_mode==0){ let bullet = databus.pool.getItemByClass('bullet', Bullet) bullet.init( this.x + this.width / 2 - bullet.width / 2, this.y - 10, 10 ) databus.bullets.push(bullet) } else if(this.shoot_mode==3){ this.shoot_3() } } //新增三发连射 shoot_3() { let bullet_1 = databus.pool.getItemByClass('bullet_1', Bullet) bullet_1.init( this.x + this.width / 2 - bullet_1.width / 2, this.y - 10, 10 ) databus.bullets.push(bullet_1) let bullet_2 = databus.pool.getItemByClass('bullet_2', Bullet) bullet_2.init( this.x + this.width / 2 - bullet_2.width / 2+20, this.y - 10, 10 ) databus.bullets.push(bullet_2) let bullet_3 = databus.pool.getItemByClass('bullet_3', Bullet) bullet_3.init( this.x + this.width / 2 - bullet_3.width / 2-20, this.y - 10, 10 ) databus.bullets.push(bullet_3) }
最主要的还是main.js这个文件,游戏的主循环和更新:update(),循环:loop(),渲染:render(),全局碰撞检测collisionDetection()等几个重要的函数都在这里面,为了增添我在上面说的一些变动,这个文件里的代码也改动了不少。
最后的总结:
这次作业的大部分时间都花在看这份原始demo的代码上了,为了搞懂这份demo的框架与运行机制花了不少时间,最主要的困难还是在于对JavaScript这门语言的不熟悉上,在编写代码的过程中犯了不少语法错误。