游戏引擎 / 系统课时

组装一个完整游戏循环

组装一个完整游戏循环

只有角色移动和碰撞,还不足以构成可以开始、达成目标并重玩的游戏。本节把输入、状态和界面组合成一个三次拾取的最小游戏循环,先证明闭环可运行,再接回角色、敌人与关卡系统。

学习目标

  • 定义一局的目标与结束条件
  • 用唯一状态入口处理拾取和重开
  • 按层次接回移动、碰撞与资源管理

让闭环小到可以一次验收

在 Canvas 下创建可见 Sprite 节点 Coin、Label Hud 和 Button Restart。Coin 有有效 UITransform,图片不为空,放在画面中央附近;Restart 放到右下角,不遮挡 Coin。创建空节点 LoopController,本例以点击 Coin 代替碰撞拾取,目标为累计三次。

最小游戏循环与重开入口

重开必须重置计数、目标位置、可见性和按钮状态。不能只把结算面板关掉,让上一局数据继续运行。先验证这个小闭环,可以把之后的故障限定在新接入的系统,而不是同时调试五种交互。

运行可重玩的拾取游戏

保存 MiniLoop.ts,挂到 LoopController,绑定三个属性。组件通过 Coin 的触摸结束事件拾取,Restart 的按钮事件重开;两个节点的编辑器事件列表不再重复接线。

ts
import { _decorator, Component, Node, Label, Button } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('MiniLoop')
export class MiniLoop extends Component {
    @property(Node) coin: Node | null = null;
    @property(Label) hud: Label | null = null;
    @property(Button) restartButton: Button | null = null;
    private count = 0;
    private won = false;
    onEnable(): void {
        this.coin?.on(Node.EventType.TOUCH_END, this.collect, this);
        this.restartButton?.node.on(Button.EventType.CLICK, this.reset, this);
    }
    onDisable(): void {
        this.coin?.off(Node.EventType.TOUCH_END, this.collect, this);
        this.restartButton?.node.off(Button.EventType.CLICK, this.reset, this);
    }
    start(): void { this.reset(); }
    private reset(): void {
        if (!this.coin || !this.hud || !this.restartButton) { this.enabled = false; return; }
        this.count = 0; this.won = false;
        this.coin.active = true; this.coin.setPosition(-100, 0, 0);
        this.hud.string = 'Coins: 0/3';
        this.restartButton.interactable = false;
    }
    private collect(): void {
        if (this.won || !this.coin || !this.hud || !this.restartButton) return;
        this.count++; // 同一入口拥有计分与结束判定
        this.won = this.count === 3;
        this.hud.string = this.won ? 'Won: 3/3' : 'Coins: ' + this.count + '/3';
        this.coin.active = !this.won;
        this.coin.setPosition((this.count - 1) * 100, 0, 0);
        this.restartButton.interactable = this.won;
    }
}

预期结果:初始显示 Coins: 0/3,依次点击移动后的 Coin,第三次显示 Won: 3/3,Coin 隐藏且 Restart 可点击。重开回到 0/3 和初始位置,可连续玩多轮,每轮都只需要三次有效点击。

按闭环接回真实玩法

把点击入口替换为经过身份去重的碰撞拾取,仍调用同一个计分规则;把固定 Coin 节点替换为对象池时,保留领取标记重置和安全回收阶段。加入敌人受伤后,生命归零进入失败结算,不能继续生成敌人或接受得分。

角色移动、相机、动画和资源加载逐项接入,每次重跑开始、达标、失败、暂停、重开和回菜单路径。记录一局状态拥有者,避免多个组件分别判断胜利。闭环稳定后再增加美术和内容量,确保功能增加不会破坏新一局的干净起点。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

组装一个完整游戏循环

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通