源码资源链接,我加了点注释,有需要的可以看下:
链接:https://pan.baidu.com/s/1Qxu85ULik8unzOtGcJCqCQ
提取码:5mxo
(function () {
let Pipe = function () {
this.h1 = Math.round(Math.random() * 220 + 100); // h1为上边管道,随机高度220-320之间
this.space = 140; // 上下方管道 空隙为140
// 下方管道长度 = 总高度 - 土地高 - 空隙 - h1高度;
this.h2 = game.canvas.height - 112 - this.space - this.h1;
this.x = game.canvas.width * 1; // 距离左侧 1个屏幕距离
this.done = true; // 此管道是否已经计过总分
game.pipeArr.push(this) // 推入管道数组
}
window.Pipe = Pipe;
Pipe.prototype.update = function () {
this.x -= 2; // 管道不断向左侧位移
if (this.x <= -52) { //当管道在屏幕中消失, 在管道队列中清除此管道
for (var i = 0; i < game.pipeArr.length; i++) {
if (game.pipeArr[i] == this) {
game.pipeArr.splice(i, 1);
i--
}
}
}
// 定义管道边界值
this.x1 = this.x;
this.x2 = this.x + 52;
this.y1 = this.h1;
this.y2 = this.h1 + this.space;
// console.log(game.bird);
//碰撞检测,在左右管道边界之间,是否在y轴上侵占管道边界
// 48为一个小鸟宽高,(里边有空白)这里定义为40为边界
if ((game.bird.x + 40 > this.x1 && game.bird.y < this.y1 && game.bird.x + 40 < this.x2) ||
(game.bird.x + 40 > this.x1 && game.bird.y + 40 > this.y2 && game.bird.x + 40 < this.x2)) {
game.Sm.enter(3) // 进入爆炸场景
}
// 计分 此管道是否已经计过分,已飞跃管道
if (this.done && game.bird.x > this.x2) {
game.score++
this.done = false; // 每个实例管道只能计一次分
}
}
Pipe.prototype.render = function () {
// 渲染上下管道,drawImage 9 个参数,第一个参数图片路径,后面四个参数图片剪切(x,y,w,h)的尺寸,最后四个参数在画布上放的位置及显示(x,y,w,h)
game.draw.drawImage(game.allImg['pipe_down'], 0, 320 - this.h1, 52, this.h1, this.x, 0, 52, this.h1);
game.draw.drawImage(game.allImg['pipe_up'], 0, 0, 52, this.h2, this.x, this.h1 + 140, 52, this.h2)
}
})()
主要参考:canvas-js实现flyBird游戏