头图

新建scripts/Game.ts,内容如下,把它挂载到Canvas节点上。拖拽Canvas/grid/bg节点到bgNode属性上,拖拽Canvas/grid/root节点到rootNode属性上。

import Grid from "./Grid"

const { ccclass, property } = cc._decorator


const GRID_SIZE = 4


@ccclass
export default class Game extends cc.Component {
    @property(cc.Node)
    private bgNode: cc.Node = null
    @property(cc.Node)
    private rootNode: cc.Node = null

    private grids: Grid[][] = []
    private gridsReversed: Grid[][] = []


    protected onLoad(): void {
        this.init()
    }


    private init() {
        const gridPrefab = this.rootNode.children[0]
        gridPrefab.active = false

        let idx = 0
        for (let col = 0; col < GRID_SIZE; col++) {
            this.grids[col] = []
            for (let row = 0; row < GRID_SIZE; row++) {
                const grid = cc.instantiate(gridPrefab)
                grid.parent = this.rootNode

                const gridComp = grid.getComponent(Grid)
                gridComp.init(this.bgNode.children[idx].getPosition())

                grid.active = true
                gridComp.num = Math.pow(2, idx + 1)

                this.grids[col][row] = gridComp
                idx++
            }
        }

        gridPrefab.destroy()

        for (let col = 0; col < GRID_SIZE; col++) {
            this.gridsReversed[col] = []
            for (let row = 0; row < GRID_SIZE; row++) {
                this.gridsReversed[col][row] = this.grids[row][col]
            }
        }
    }
}

脚本属性设置

运行项目,会发现16个格子依次显示了从26553616个数字,并且有不同的文字颜色和背景颜色。

格子数字调试

这是因为加了调试的代码,编辑scripts/Game.ts,删除下面两行调试代码,再次运行项目就不会显示任何格子了。

删除调试代码

编辑scripts/Game.ts,添加DURATION常量设置缓动时间。

const GRID_SIZE = 4
const DURATION = 0.1

添加randGrid方法用于随机显示格子。

private randGrid() {
    const randGrids: Grid[] = []
    for (const rowGrids of this.grids) {
        for (const grid of rowGrids) {
            if (!grid.num) randGrids.push(grid)
        }
    }

    const grid = randGrids[this.randRange(0, randGrids.length - 1)]
    grid.num = 2
    grid.node.scale = 0
    cc.tween(grid.node).to(DURATION, { scale: 1 }).start()
}


// 整数范围随机 [min, max]
private randRange(min: number, max: number): number {
    return Math.round(Math.random() * (max - min) + min)
}

添加start方法,调用randGrid方法两次,这样程序运行时就会随机显示两个格子。

protected start(): void {
    this.randGrid()
    this.randGrid()
}

随机显示格子


mirahs
1 声望0 粉丝