因为业务核心点为营销,无需开发大型重量级H5游戏,所以选择其中较为轻量的框架。而Hilo的设计思路更加偏向前端开发者以及简单的营销活动小游戏。经过压缩后体积约65KB,相对于Egret(白鹭)引擎、Unitity已经算十分的轻量了。并且拥有中文文档,对于中文开发者来说十分友好,且已经经历多届阿里巴巴双十一,年中大促互动营销活动考验。对于我们业务来说,只需要适配对canvas和css3支持度良好的高级浏览器或者webview,直接使用Hilo基础渲染器而无需在引入其他模块。
预先加载各种图片资源,提升用户体验。
let imgs = [{
id: 'bg',
src: 'ingots/bg.png'
},
{
id: 'copper',
src: 'ingots/copper.png'
},
{
id: 'silver',
src: 'ingots/silver.png'
},
{
id: 'gold',
src: 'ingots/gold.png'
},
{
id: 'boom',
src: 'ingots/boom.png'
},
{
id: 'god',
src: 'ingots/god.png'
},
{
id: 'score0',
src: 'ingots/score0.png'
}
];
this.queue = new Hilo.LoadQueue();
this.queue.add(imgs);
this.queue.on('complete', this.onComplete.bind(this));
this.queue.on('error', this.error.bind(this));
this.queue.start();
舞台是一个各种图形、精灵动画等的总载体。所有用Hilo创建的可见的对象都必须添加到舞台或其子容器后,才会被渲染和显示出来。 舞台实质上也是一个容器Container,不过它是一个顶级容器。它除开拥有普通容器的功能,它还拥有一些特殊属性和方法。
// 舞台
this.stage = new Hilo.Stage({
renderType:'canvas',
width: this.width,
height: this.height,
scaleX: this.scale,
scaleY: this.scale,
container: this.page
});
Hilo对象默认不允许触发点击等事件,需要先给舞台对象启用。下面这段代码表示启用对用户手指开始触摸、移动、停止触摸等事件的事件监听。
this.stage.enableDOMEvent([Hilo.event.POINTER_START, Hilo.event.POINTER_MOVE, Hilo.event.POINTER_END]);
用于不断刷新渲染页面动画
// 启动定时器刷新页面 参数为帧率
this.ticker = new Hilo.Ticker(60)
// 舞台添加到定时队列中
this.ticker.addTick(this.stage)
// 添加动画类到定时队列
this.ticker.addTick(Hilo.Tween);
//启动ticker
this.ticker.start(true);
财神对象
this.god = new God({
id: 'god',
img: this.asset.god,
height: this.asset.god.height,
width: this.asset.god.width,
x: this.width / 2 - this.asset.god.width / 2,
y: this.height - this.asset.god.height + 30
}).addTo(this.stage, 1);
Hilo.util.copy(this.god, Hilo.drag);
this.god.startDrag([-this.asset.god.width / 4, this.height - this.asset.god.height + 30, this.width - this.asset.god.width / 2, 0]);
铜币、银元宝、金元宝、炸弹对象
this.yuanbao = new Yuanbao({
id: 'Yuanbao',
height: this.height,
width: this.width,
yuanbaoSpeed: this.yuanbaoSpeed,
createSpeed: this.createSpeed,
pointerEnabled: false, // 不关闭事件绑定 无法操作舞台
yuanbaoList: [this.asset.copper, this.asset.silver, this.asset.gold,this.asset.boom]
}).addTo(this.stage, 2)
//舞台更新
this.stage.onUpdate = this.onUpdate.bind(this);
舞台更新判断财神对象碰撞计算得分
onUpdate() {//舞台更新
if (this.gameStatus == 'ready') {
return
}
this.yuanbao.children.forEach(item => {
if (this.god.checkCollision(item)) {
// 碰撞了
item.over();
this.score += item.score;
//监听
this.onScoreChange(this.score);
switch (item.score) {
case -10:
this.god.addScore(this.asset.score0)
break;
default:
break;
}
}
})
}
实现元宝对象下落的动画,用Hilo.Tween.to方法来控制对象移动。
let hold = new YuanbaoItem({
image: this.yuanbaoList[index],
rect: [0, 0, this.yuanbaoList[index].width, this.yuanbaoList[index].height]
}).addTo(this);
hold.x = this.random(100, (this.width - 100));
hold.y = -300 * Math.random();
hold.score = this.score[index]
this.tween.to(hold, {
y: this.height + 200
}, {
duration: 1400 / this.yuanbaoSpeed * 1000,
loop: false,
onComplete: () => {
hold.removeFromParent()
}
});
https://zefey.com/game/index.html