文件夹规范
Constants.ts 用于控制全局
GameScene
:游戏入口文件
gameManager
是控制全局的变量,讲入口文件赋值给它,这样其他组件引用Hello的时候,可以使用GameScene里的属性.
GameState
是一个enum类型,其中每个值都是上一个值+1,用于控制游戏状态.
gameState
表示当前游戏的状态.
import GameScene from "../../scripts/GameScene";
export enum GameState {
READY = 1,
PLAYING,
PAUSE,
OVER,
}
class Constants {
private static _instance: Constants = null;
constructor() {
return Constants._instance;
}
public static get Instance(): Constants {
return this._instance || new Constants()
}
public gameManager: GameScene = null;
public gameState: GameState = GameState.READY;
}
let hello = Constants.Instance
export { hello as Constants }
在Player.ts里使用入口文件的函数:
const {ccclass, property} = cc._decorator;
import { Hello } from "./hello";
@ccclass
export default class Player extends cc.Component {
onLoad(){
Hello.gameManager.setNewCoin()
}
}
GameScene.ts
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import { Hello } from "./hello";
import YellowBall from "./yellowball";
const { ccclass, property } = cc._decorator;
@ccclass
export default class GameScene extends cc.Component {
@property(cc.Prefab)
coinPrefab: cc.Prefab = null;
@property(YellowBall)
player: YellowBall = null;
public starNode: cc.Node = null;
setNewCoin() {
let newCoin = cc.instantiate(this.coinPrefab);
this.node.addChild(newCoin);
newCoin.setPosition(this.getNewCoinPosition())
newCoin.getComponent('YellowBall').GameScene = this;
this.starNode = newCoin;
}
getNewCoinPosition() {
let rand = Math.random() - 0.5;
let randY;
rand ? randY = -215 : randY = 215;
return cc.v2(400, randY)
}
onLoad() {
Hello.gameManager = this;
this.setNewCoin();
}
}