【实例简介】
1. 点击工具栏左侧 “云开发” 按钮,根据提示在控制台中开通云服务
2. 根据提示创建第一个环境(注:初始可免费拥有两个环境,建议一个为测试环境,一个为正式环境,分别命名为 test 和 release)
3. 在控制台中切换到 “数据库” 管理页,创建第一个名为 “score” 的集合,用于存放分数
4. 在工具编辑器目录树中,右键目录 "cloudfunction" 选择 “更多设置”,在打开的窗口上方下拉选择刚创建的环境
5. 在编辑器 "cloudfunction" 目录下,右击目录 “login”,选择新建并上传该云函数,该云函数负责获取用户 openid
6. 在编辑器 "cloudfunction" 目录下,右击目录 “uploadScore”,选择新建并上传该云函数,该云函数负责记录用户分数到数据库
7. 体验小游戏!
【实例截图】
【核心代码】
import Player from'./player/index'
import Enemy from'./npc/enemy'
import BackGround from'./runtime/background'
import GameInfo from'./runtime/gameinfo'
import Music from'./runtime/music'
import DataBus from'./databus'
let ctx = canvas.getContext('2d')
let databus =newDataBus()
/**
* 游戏主函数
*/
exportdefaultclass Main {
constructor() {
this.restart()
}
restart() {
databus.reset()
canvas.removeEventListener(
'touchstart',
this.touchHandler
)
this.bg =newBackGround(ctx)
this.player =newPlayer(ctx)
this.gameinfo =newGameInfo()
this.music =newMusic()
window.requestAnimationFrame(
this.loop.bind(this),
canvas
)
}
/**
* 随着帧数变化的敌机生成逻辑
* 帧数取模定义成生成的频率
*/
enemyGenerate() {
if( databus.frame % 30 === 0 ) {
let enemy = databus.pool.getItemByClass('enemy', Enemy)
enemy.init(6)
databus.enemys.push(enemy)
}
}
// 全局碰撞检测
collisionDetection() {
let that =this
databus.bullets.forEach((bullet) => {
for( let i = 0, il = databus.enemys.length; i < il;i ) {
let enemy = databus.enemys[i]
if( !enemy.isPlaying && enemy.isCollideWith(bullet) ) {
enemy.playAnimation()
that.music.playExplosion()
bullet.visible =false
databus.score = 1
break
}
}
})
for( let i = 0, il = databus.enemys.length; i < il;i ) {
let enemy = databus.enemys[i]
if(this.player.isCollideWith(enemy) ) {
databus.gameOver =true
break
}
}
}
//游戏结束后的触摸事件处理逻辑
touchEventHandler(e) {
e.preventDefault()
let x = e.touches[0].clientX
let y = e.touches[0].clientY
let area =this.gameinfo.btnArea
if( x >= area.startX
&& x <= area.endX
&& y >= area.startY
&& y <= area.endY )
this.restart()
}
/**
* canvas重绘函数
* 每一帧重新绘制所有的需要展示的元素
*/
render() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.bg.render(ctx)
databus.bullets
.concat(databus.enemys)
.forEach((item) => {
item.drawToCanvas(ctx)
})
this.player.drawToCanvas(ctx)
databus.animations.forEach((ani) => {
if( ani.isPlaying ) {
ani.aniRender(ctx)
}
})
this.gameinfo.renderGameScore(ctx, databus.score)
}
// 游戏逻辑更新主函数
update() {
this.bg.update()
databus.bullets
.concat(databus.enemys)
.forEach((item) => {
item.update()
})
this.enemyGenerate()
this.collisionDetection()
}
// 实现游戏帧循环
loop() {
databus.frame
this.update()
this.render()
if( databus.frame % 20 === 0 ) {
this.player.shoot()
this.music.playShoot()
}
// 游戏结束停止帧循环
if( databus.gameOver ) {
this.gameinfo.renderGameOver(ctx, databus.score)
this.touchHandler =this.touchEventHandler.bind(this)
canvas.addEventListener('touchstart',this.touchHandler)
return
}
window.requestAnimationFrame(
this.loop.bind(this),
canvas
)
}
}
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)