之前的canvas小游戏系列欢迎大家戳:
如标题,这个游戏大家也玩过,随处可见,左右方向键控制财神移动,接住从天而降的金元宝等,时间一到,则游戏结束。先来看一下效果:
相比于之前的雷霆战机要打出四处飞的子弹,这次元素的运动轨迹就很单一了,垂直方向的珠宝和水平移动的财神爷,类似于之前的代码,这里就说一下关键步骤点吧:
1、键盘控制水平移动的财神爷
这个很简单,同理于《VUE+Canvas 实现桌面弹球消砖块小游戏》滑块的控制:
drawCaishen() {
let _this = this;
_this.ctx.save();
_this.ctx.drawImage(
_this.caishenImg,
_this.caishen.x,
_this.caishen.y,
120,
120
);
_this.ctx.restore();
},
moveCaishen() {
this.caishen.x += this.caishen.dx;
if (this.caishen.x > this.clientWidth - 120) {
this.caishen.x = this.clientWidth - 120;
} else if (this.caishen.x < 0) {
this.caishen.x = 0;
}
}
2、从天而降的珠宝
这个也很简单,但要注意的是,珠宝的初始x值不能随机取0~clientWidth了,因为这样很容易造成珠宝堆积在一起,影响了游戏的可玩性,所以珠宝最好是分散在不同的轨道上,这里我们把画布宽度分为5条轨道,初始珠宝的时候,我们就把珠宝分散在轨道上,并且y值随机在一定高度造成参差。而后新生成的珠宝都依据轨道分布来生成,避免珠宝挤在一起。
generateTreasure() {
let _this = this;
if (_this.treasureArr.length < MaxNum) {
let random = Math.floor(Math.random() * TreasureNames.length);
let channel = _this.getRandomArbitrary(1, 5);
_this.treasureArr.push({
x: _this.channelWidth * (1 / 2 + (channel - 1)) - 30,
y: 0,
name: TreasureNames[random],
speed: _this.getRandomArbitrary(2, 4)
});
}
},
filterTreasure(item) {
let _this = this;
if (
item.x <= _this.caishen.x + 110 &&
item.x >= _this.caishen.x &&
item.y > _this.caishen.y
) {
// 判断和财神的触碰范围
_this.score += _this.treasureObj[item.name].score;
return false;
}
if (item.y >= _this.clientHeight) {
return false;
}
r