Phaser
是一个强大的2D游戏开发框架,其专注于HTML5游戏开发。Phaser提供了许多功能强大的API,使得游戏开发变得更加容易。
Vue
是一个流行的JavaScript框架,其专注于构建交互式的单页面应用程序。这篇文章将介绍如何在Vue中集成Phaser来构建高质量的游戏应用程序。
安装vue cli
npm install -g @vue/cli
创建新项目
$ vue create test1
? Your connection to the default npm registry seems to be slow.
? Your connection to the default npm registry seems to be slow.
Use https://registry.npmmirror.com for faster installation? Yes
? Please pick a preset: (Use arrow keys)
? Please pick a preset: Default ([Vue 3] babel, eslint)
✨ Creating project in D:\wangqi\phaser3\demo\test1.
🗃 Initializing git repository...
⚙️ Installing CLI plugins. This might take a while...
added 864 packages in 31s
🚀 Invoking generators...
📦 Installing additional dependencies...
added 103 packages in 8s
⚓ Running completion hooks...
📄 Generating README.md...
🎉 Successfully created project test1.
👉 Get started with the following commands:
$ cd test1
$ npm run serve
安装Phaser
$ cd test1
$ npm uninstall phaser
up to date, audited 968 packages in 3s
found 0 vulnerabilities
效果展示
部分主要文件代码
main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
App.vue
<script setup>
import Home from '@/components/HomeView'
</script>
<template>
<Home />
</template>
HomeView.vue
<script setup>
import PhaserContainer from '@/components/PhaserContainerView'
</script>
<template>
<Suspense>
<PhaserContainer />
<template #fallback>
<div class="placeholder">
Downloading ...
</div>
</template>
</Suspense>
</template>
PhaserContainerView.vue
<script setup>
import { onMounted, onUnmounted } from 'vue'
let gameInstance = null
const containerId = 'game-container'
const game = await import(/* webpackChunkName: "game" */ '@/game/game')
onMounted(() => {
gameInstance = game.launch(containerId)
})
onUnmounted(() => {
gameInstance.destroy(false)
})
</script>
<template>
<div :id="containerId" />
</template>
game.js
import Phaser from 'phaser'
import BootScene from '@/game/scenes/BootScene'
import PlayScene from '@/game/scenes/PlayScene'
function launch(containerId) {
return new Phaser.Game({
type: Phaser.AUTO,
width: 800,
height: 600,
parent: containerId,
physics: {
default: 'arcade',
arcade: {
debug: false
}
},
scene: [BootScene, PlayScene]
})
}
export default launch
export { launch }
BootScene.js
import { Scene } from 'phaser'
export default class BootScene extends Scene {
constructor () {
super({ key: 'BootScene' });
}
preload () {
}
create () {
this.scene.start('PlayScene')
}
}
PlayScene.js
import { Scene } from 'phaser'
export default class PlayScene extends Scene {
constructor () {
super({ key: 'PlayScene' })
}
create () {
this.showMsg = this.add.text(16, 16, 'Hello Phaser!', { fontSize: '32px', fill: '#fff' });
}
update () {
}
}
本节完整代码下载地址
https://github.com/biwow/phaser3/tree/main/code/1