🚀 cocos进阶语法

2025-10-11
795 字约 3 分钟
...

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) :图片、...
学习
八股文2026-07-30
一、TypeScript与类型系统(20题)
1\. 在定义AI接口返回的嵌套数据结构(如多轮对话、工具调用结果)时,如何用TypeScript的泛型与条件类型实现灵活的类型推导? 场景:为“AI助手”定义统一的消息类型系统,需兼容不同模型供应商(OpenAI/Anthropic)及内部(Moonshot)的返回格式。 核心答案: 构建一个以泛型为基础、条件类型为分支的层次化类型系统。核心是利用泛型参数化“消息内容”、“工具调用”和“提供商”,再通过条件类型精确匹配不同场景下的数据...
学习
godot2026-07-27
Godot 4 常用 UI 节点详解
Godot 4 常用 UI 节点详解 在 Godot 4 中,UI 系统基于 Control(控件) 节点构建。所有 UI 节点都继承自 Control,形成一棵完整的 UI 树。与游戏引擎中常见的"Canvas + DOM"模式不同,Godot 的 UI 系统是声明式的——你在场景中搭好节点树,引擎自动完成布局计算。 一、布局系统:Container 家族 Container 是 Godot UI 的 骨架 。它决定了子节点的大小和位...
学习
前端2026-07-17
HTML Form 可以把 POST 响应加载进 iframe
在接入支付验证、身份认证或第三方授权页面时,我们经常会遇到这样的流程: 1. 后端返回一个第三方接口地址。 2. 这个地址必须通过 请求访问。 3. 接口返回 HTML,或者重定向到真正的验证页面。 4. 验证页面需要嵌入当前网站,而不是打开新标签页。 5. 验证完成后,当前页面继续执行后续业务。 第一次遇到这个需求,很容易想到: 但涉及第三方支付时,这种方式通常会遇到 CORS、Cookie、重定向和跨域页面读取限制。 实际上,HTM...
学习

评论

请登录后发表评论

去登录
加载评论中...

目录