微信小程序与微信小游戏是不同的,区别在于:
1 账号类型不同,申请微信小程序号的时候需要选择类别,小程序与小游戏是不同的类别。 2 小程序的appId不能用于小游戏。反之亦然。 3 小游戏里没有 button image view text等小程序的组件 4 小程序里可以使用canvas
那么是不是可以在小程序里使用canvas开发游戏呢?答案是肯定的。但不建议这么做。因为在小程序里开发游戏。它的性能不如小游戏。
不过,如果在小程序里开发比较简单的游戏,还是可以的,比如推箱子:
以下是在小程序里开发推箱子的一些关键思路:
1 把屏幕平均分为一些格子。渲染时,把数组替换成相应的图片。
const n = map.length
const size = width / n
map.forEach((line, y) => {
line.forEach((item, x) => {
if (item != 0) {
ctx.drawImage(images.filter(img => {
return img.id === item
})[0].img, x * size, y * size, size, size)
}
})
})
2 每关用数组来表示
const stages = [
[
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 8, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 3, 0, 0, 1],
[1, 0, 1, 3, 3, 3, 1, 1],
[1, 3, 1, 2, 3, 0, 0, 1],
[1, 1, 3, 3, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
],
[
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 3, 0, 2, 1],
[1, 0, 1, 0, 3, 1, 3, 1],
[1, 3, 1, 3, 3, 0, 8, 1],
[1, 0, 0, 3, 0, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
],
[
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1, 8, 1],
[1, 0, 1, 0, 3, 0, 0, 1],
[1, 0, 0, 0, 1, 3, 1, 1],
[1, 0, 1, 3, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 0, 2, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
],
]
module.exports = {
stages
}
3 加载资源
const load = (image_id_array, canvas, callback, on_progress) => {
const loaded_images = [];
image_id_array.forEach(element => {
const img = canvas.createImage();
img.src = `../../assets/${element}.png`
img.onload = () => {
console.log('load')
loaded_images.push({
id: element,
img: img
});
if (on_progress) {
const progress = parseFloat((loaded_images.length / image_id_array.length).toFixed(2))
on_progress(progress)
}
if (loaded_images.length === image_id_array.length) {
callback(loaded_images)
}
}
});
}
module.exports = {
load
}
4 碰撞检测,通过判断数组中的位置是否重叠来实现。也就是检测玩家角色的坐标到达目标后的坐标是否已经有了其他角色。
const next_to = [to[0] - from[0] + to[0], to[1] - from[1] + to[1]]
//
5 为了可以随时重新开始,需要在传值的时候,传一个全新的数组,而非引用。
const map = JSON.parse(JSON.stringify(stages[stage_index]));
this.setData({
map: map
})