🚀 cocos进阶语法

2025-10-11
7953 分钟
...

1. 组件设计与脚本复用

在 Cocos Creator 中,一切都是组件
你可以把通用逻辑封装成独立组件,实现模块化开发。

@ccclass('AutoMove')
export class AutoMove extends Component {
    @property speed = 100;
    @property direction = new Vec3(1, 0, 0);

    update(dt: number) {
        this.node.translate(this.direction.multiplyScalar(this.speed * dt));
    }
}

建议
把“功能性逻辑”(移动、旋转、漂浮、点击反应等)做成通用组件,避免在业务逻辑脚本里重复写。


2. 单例与全局管理器

大型项目通常需要全局控制器,比如音效、玩家数据、网络。

@ccclass('GameManager')
export class GameManager extends Component {
    private static _instance: GameManager;
    public static get instance() { return this._instance; }

    onLoad() {
        GameManager._instance = this;
    }

    playSound(name: string) {
        console.log(`播放音效:${name}`);
    }
}

使用:

GameManager.instance.playSound('jump');

建议
使用“单例模式”集中管理音效、事件、UI、对象池等,减少节点层级耦合。


3. 动画系统与状态机

3.1 动画控制器(Animation)

import { Animation } from 'cc';

const anim = this.node.getComponent(Animation);
anim.play('run');

3.2 动画事件回调

anim.on(Animation.EventType.FINISHED, () => {
    console.log('动画播放完成');
});

3.3 状态机实现思路

enum PlayerState { Idle, Run, Attack }

@ccclass('Player')
export class Player extends Component {
    state = PlayerState.Idle;

    changeState(newState: PlayerState) {
        if (this.state === newState) return;
        this.state = newState;
        this.updateAnim();
    }

    updateAnim() {
        const anim = this.node.getComponent(Animation);
        switch (this.state) {
            case PlayerState.Run: anim.play('run'); break;
            case PlayerState.Attack: anim.play('attack'); break;
            default: anim.play('idle'); break;
        }
    }
}

4. 对象池(Object Pool)

频繁创建/销毁节点会导致性能抖动,应使用对象池。

import { instantiate, Prefab } from 'cc';

export class BulletPool {
    pool: Node[] = [];
    prefab: Prefab;

    constructor(prefab: Prefab) {
        this.prefab = prefab;
    }

    get() {
        return this.pool.length > 0 ? this.pool.pop() : instantiate(this.prefab);
    }

    put(node: Node) {
        node.removeFromParent();
        this.pool.push(node);
    }
}

5. 资源加载与内存管理

5.1 预加载资源

resources.preload('enemy/enemy01', Prefab);

5.2 释放资源

resources.release('enemy/enemy01');

5.3 动态加载远程图片

import { assetManager, SpriteFrame, Texture2D } from 'cc';

assetManager.loadRemote<Texture2D>('https://example.com/test.png', (err, tex) => {
    const sf = new SpriteFrame();
    sf.texture = tex;
    this.node.getComponent(Sprite).spriteFrame = sf;
});

6. UI 事件与交互

6.1 点击事件

button.node.on(Button.EventType.CLICK, this.onClick, this);

6.2 自定义全局事件总线

import { EventTarget } from 'cc';

export const GlobalEvent = new EventTarget();

// 派发事件
GlobalEvent.emit('playerDead', { id: 123 });

// 监听事件
GlobalEvent.on('playerDead', (data) => console.log(data.id), this);

7. 游戏架构与模块化设计

7.1 模块划分建议

assets/
 ├── core/         # 引擎层封装
 ├── managers/     # 管理器 (UIManager, GameManager, AudioManager)
 ├── components/   # 公共组件
 ├── scenes/       # 游戏场景
 ├── prefabs/      # 预制体
 ├── scripts/      # 逻辑脚本
 └── utils/        # 工具函数

7.2 UI 管理器示例

@ccclass('UIManager')
export class UIManager extends Component {
    private static _inst: UIManager;
    static get inst() { return this._inst; }

    private uiMap: Map<string, Node> = new Map();

    onLoad() { UIManager._inst = this; }

    show(name: string, prefab: Prefab) {
        if (this.uiMap.has(name)) return;
        const ui = instantiate(prefab);
        this.node.addChild(ui);
        this.uiMap.set(name, ui);
    }

    close(name: string) {
        const ui = this.uiMap.get(name);
        if (ui) ui.destroy();
        this.uiMap.delete(name);
    }
}

8. 性能优化技巧

  1. 对象池:减少频繁 instantiate/destroy
  2. Batch 合批:同贴图 Sprite 自动批处理
  3. 减少节点层级:UI 超过 500 节点容易掉帧
  4. 少用透明 / 模糊特效:性能消耗大
  5. 合理分帧更新:把大任务拆分执行
  6. Profiler 工具Ctrl + Shift + F7 打开性能监控

9. 构建与发布

  • Web 平台建议使用 压缩 + 混淆 + 分包加载

  • Android / iOS 使用 热更新机制(Asset Bundle)

  • 使用命令行构建:

    cocos-cli build --platform web-mobile --config-path ./build_config.json

10. 结语

Cocos Creator 3.x 提供了现代前端式开发体验:

  • 模块化 TypeScript
  • ES 导入机制
  • 更强的 3D 渲染与性能优化
  • 统一的资源与节点系统

掌握组件化思维 + 管理器模式 + 优化技巧
你就能构建出稳定、流畅、可扩展的游戏框架。

如果您觉得这篇文章有帮助,请点个赞吧~

分享文章

相关文章

更多文章 →
cocos2026-07-22
🎯 Cocos Creator 生命周期详解
Cocos Creator 生命周期详解 一、前言 Cocos Creator 作为主流的游戏开发引擎,其组件化架构的核心就是 生命周期回调函数 。理解这些回调的触发时机、执行顺序和使用场景,是写出高质量游戏逻辑的基础。 本文基于 Cocos Creator 3.x ,系统梳理从引擎启动到场景切换、从节点创建到销毁的完整生命周期。 二、组件生命周期回调总览 Cocos Creator 的生命周期回调按触发顺序排列如下: | 回调函数 |...
学习
cocos2026-07-22
🚀 Cocos Creator 新手入门指南
一、Cocos Creator 是什么 Cocos Creator 是一款专注于 2D 和 3D 游戏开发的引擎,由 Cocos 团队开发。它的核心理念是 组件化开发 ——把游戏中的每个功能拆成独立的组件,像搭积木一样组合起来。 主要特点 : 完全免费,支持发布到 Web、iOS、Android、桌面等多平台 使用 TypeScript 编写脚本,对前端开发者非常友好 编辑器可视化操作,所见即所得 内置资源管理、动画系统、UI 系统、物...
学习
cocos2025-09-23
📘 Cocos Creator 语法入门文档
📘 Cocos Creator 语法入门文档 1. 基础概念 Cocos Creator 使用 TypeScript/JavaScript 作为主要开发语言,游戏逻辑通常通过脚本来驱动。主要模块: 节点 (Node) :场景中的基本元素,可以理解为游戏对象。 组件 (Component) :附加到节点上的脚本/功能,比如渲染、物理、脚本逻辑。 场景 (Scene) :游戏运行的基本单位,包含多个节点。 资源 (Assets) :图片、...
学习
AI2026-09-01
Deep Agents 01:何为 Agent Harness,以及如何开始
1、本篇任务:完成一份多步骤、带证据的技术调研 普通客服 Agent 的问题短、工具少、输出即时。技术调研或编码任务会持续很久,产生计划、搜索结果、文件和中间结论。Deep Agents 在 LangChain/LangGraph 之上预装规划、虚拟文件系统、上下文压缩和子 Agent,适合这类开放任务。 本课让 Agent 比较两种向量数据库,并交付一份可验证报告。 2、什么时候需要 Deep Agent 满足以下两项以上再考虑:任务...
学习
AI2026-09-01
Deep Agents 02:子 Agent、虚拟文件系统与长期记忆
1、本篇任务:让主管只看结论,让子 Agent 处理细节 技术调研会产生几十次搜索和大量文件。如果全部进入主管上下文,真正的目标会被噪音淹没。本课用两个子 Agent: 收集证据, 检查结论;主管负责计划与最终合成。 2、什么时候委派,什么时候直接调用工具 适合委派:子任务有多步;需要专门提示或工具;会产生大量中间结果;只需返回有限结论。不适合:一步查询;主管需要全部中间上下文;协调成本超过任务本身。 3、配置专门子 Agent Pyt...
学习
AI2026-09-01
Deep Agents 03:生产化、Sandbox、权限与上线验收
1、本篇任务:让 Deep Agent 在隔离环境中分析代码 只读研究 Agent 风险有限;编码 Agent 需要读写文件、安装依赖和执行测试。本课不讲如何让模型写更漂亮的代码,只讲执行环境、权限、恢复和上线验收。 2、先做威胁模型 资产包括源代码、用户文件、云凭证、生产网络和发布权限;攻击入口包括用户消息、仓库内容、网页、依赖包、MCP 返回和命令输出。 Prompt injection 不是靠一句 system prompt 解决...
学习

评论

请登录后发表评论

去登录
加载评论中...

目录