Cocos Creator 入门:从零搭建第一个 2D 场景

从创建项目、认识节点与组件,到编写第一个 TypeScript 移动脚本,完成一个可运行的 Cocos Creator 2D 场景。

Cocos Creator 入门:从零搭建第一个 2D 场景

第一次接触 Cocos Creator,不需要先做复杂玩法。先完成角色能在一个场景里移动这个小目标,就能把项目、场景、节点、组件、脚本和预览这条主线串起来。

本文目标

完成后你会拥有一个可运行的 2D 场景,并能使用 WASD 或方向键控制 Player 节点移动。

1. 创建空项目

在 Cocos Dashboard 中点击 New,选择空项目模板,语言选择 TypeScript,填写项目名称和目录后创建并打开。编辑器里最常用的四个面板是:

  • Assets:项目资源、脚本和场景文件。
  • Hierarchy:当前场景的节点树。
  • Scene:可视化摆放节点的位置。
  • Inspector:配置选中节点的属性与组件。

建议先在 assets/scenes 下新建并保存 Game.scene。每完成一个小步骤就保存一次,后面调试会轻松很多。

2. 搭出最小场景

在 Hierarchy 中建立下面这棵节点树:

text
Canvas
├─ Background
├─ Player
└─ UI
   └─ TipLabel

Player 可以先使用一个 Sprite 或 Color Sprite 作为占位。现在不必纠结美术资源,先确保这个节点能够被脚本控制。

3. 理解节点、组件和脚本

  • Node 是场景中的对象,例如 Player、按钮、敌人。
  • Component 是挂在 Node 上的能力,例如 Sprite、Label、Collider2D。
  • Script Component 是我们用 TypeScript 写出的自定义能力。

一个实用的习惯是让一个脚本只负责一件事。PlayerController 只处理玩家移动,分数和弹窗留给别的组件处理。

4. 编写移动脚本

在 Assets 面板中新建 TypeScript 文件 PlayerController.ts:

text
import { _decorator, Component, EventKeyboard, input, Input, KeyCode, Vec3 } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {
  @property
  speed = 260;

  private readonly pressedKeys = new Set<KeyCode>();
  private readonly direction = new Vec3();

  onEnable() {
    input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
  }

  onDisable() {
    input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
  }

  private onKeyDown(event: EventKeyboard) {
    this.pressedKeys.add(event.keyCode);
  }

  private onKeyUp(event: EventKeyboard) {
    this.pressedKeys.delete(event.keyCode);
  }

  update(deltaTime: number) {
    const x = Number(this.pressedKeys.has(KeyCode.KEY_D)) - Number(this.pressedKeys.has(KeyCode.KEY_A));
    const y = Number(this.pressedKeys.has(KeyCode.KEY_W)) - Number(this.pressedKeys.has(KeyCode.KEY_S));
    if (x === 0 && y === 0) return;

    this.direction.set(x, y, 0).normalize();
    this.node.setPosition(
      this.node.position.x + this.direction.x * this.speed * deltaTime,
      this.node.position.y + this.direction.y * this.speed * deltaTime,
      this.node.position.z,
    );
  }
}

选中 Player 节点,在 Inspector 点击 Add Component,然后选择 Custom Script 和 PlayerController。保存场景后点击顶部预览按钮,使用 WASD 移动角色。

5. 为什么在 onEnable 和 onDisable 中监听事件

场景切换、节点禁用或销毁后,旧事件监听如果没有移除,容易留下重复响应。将注册与解绑成对放在组件生命周期中,能让行为更清晰,也方便日后复用脚本。

6. 初学者常见问题

  1. 脚本编译正常但没有效果:确认脚本真正挂在了 Player 节点。
  2. 移动太快或太慢:位移必须乘 deltaTime,否则不同帧率会改变速度。
  3. 场景修改没有保存:保存场景后再预览。
  4. 组件职责混乱:输入、移动、分数、动画可以逐步拆成独立脚本。

下一步

下一篇把这个角色改成可触控对象,并加入碰撞和计分。这样就从能动进入到有玩法循环。

参考