摘要
CocosCreator 物理小遊戲實戰的視頻教程也開更啦!來嗶哩嗶哩關注 KUOKUO 一起學習吧!
正文
使用版本
CocosCreator 版本 2.3.4
資源劃分
素材導入後進行資源分類,我這裏將其分爲 game 文件夾與 ui 文件夾,對應遊戲場景使用資源和顯示 UI 資源。
靜態單例管理
UIManager 與 GameManger 分別綁定至管理節點,兩者通訊靠 StaticInstance 腳本。
import GameManager from "./GameManager"
import UIManager from "./UIManager"
export class StaticInstance {
static gameManager: GameManager | undefined = undefined
static uiMannager: UIManager | undefined = undefined
static setGameManager(context: GameManager) {
StaticInstance.gameManager = context
}
static setUIManager(context: UIManager) {
StaticInstance.uiMannager = context
}
}
兩個 Manager 腳本的 onLoad 中傳入實例,在後面就可以相互調用了。
import { StaticInstance } from "./StaticInstance"
const {ccclass, property} = cc._decorator
@ccclass
export default class GameManager extends cc.Component {
onLoad() {
StaticInstance.setGameManager(this)
}
}
在 start 及其以後即可訪問實例。
import { StaticInstance } from "./StaticInstance"
const {ccclass, property} = cc._decorator
@ccclass
export default class UIManager extends cc.Component {
onLoad() {
StaticInstance.setUIManager(this)
}
start () {
console.log(StaticInstance.gameManager)
}
}
這樣就可以實現 UIManager 與 GameManager 的相互調用。
繼承UIBase
我們有 6 個 UI 要進行管理,每個 UI 都應該有顯示與隱藏的方法,故抽出其共有屬性與方法,實現一個 UIBase,讓 6 個 UI 腳本去繼承 UIBase 即可。
const {ccclass, property} = cc._decorator
@ccclass
export default class UIBase extends cc.Component {
@property({
displayName: '初始顯隱狀態'
})
isShowInit: boolean = false
onLoad() {
this.isShowInit ? this.show() : this.hide()
}
show() {
this.node.active = true
}
hide() {
this.node.active = false
}
}
StartMenu製作
拖入對應的 ui 圖片完成佈局,然後做成預製體。
聲明兩個按鈕屬性,寫下幾個方法,注意是繼承 UIBase 的。
import UIBase from "./UIBase"
import UIManager from "../UIManager"
const {ccclass, property} = cc._decorator
@ccclass
export default class StartMenu extends UIBase {
@property(cc.Node) startButton: cc.Node = undefined
@property(cc.Node) levelSelectButton: cc.Node = undefined
onLoad() {
super.onLoad()
}
show() {
super.show()
}
init(uiManager: UIManager) {
}
}
如下 UML 圖,在 StartMenu 中就擁有了這些屬性方法。
結語
視頻已經開始更了哦,視頻鏈接爲:https://www.bilibili.com/video/BV1ck4y167mR
2020!我們一起進步!O(∩_∩)O~~