Cocos 开发篇
用 Creator 3.8.4 从空项目做出一个能在浏览器运行的小游戏。
1. 编辑器、场景与组件
这篇做一个两条轨道的「接星星」小游戏。点开始后,星星在左右轨道交替下落。玩家用左右按钮移动,同轨才得分,第五颗落地后结算。
- 用 Creator 3.8.4 建一个 2D 项目,保存主场景为
Main。使用场景的 Canvas 和 UI 相机。 - 在 Canvas 下建
Playfield,位于局部原点。在 Playfield 下建PlayerSprite,给它绑定一张可见的图,初始位置设为(-120, -160, 0)。 - 在 Canvas 下建立
HUDLabel,放在(0, 300, 0),初始文字设为「点开始」。再建 Left、Right 和 Start 三个 Button,分别用「左」「右」「开始」作按钮文字。Left 和 Right 在 y = -260,x 分别为 -120 和 120。Start 可放在(0, -340, 0)。
Canvas(稍后挂 CatchGame)
├─ Playfield
│ └─ Player(Sprite)
├─ HUD(Label)
├─ Left(Button)
├─ Right(Button)
└─ Start(Button)
先跑一次预览,确认角色、分数文字和按钮都能看见,再接脚本。若界面显示不全,检查项目的设计分辨率和 Canvas。可以先用 720 × 1280 的竖屏布局。
2. 用 Prefab 生成下落物
- 新建
DropSprite 节点,为它选择一张图。把节点从层级拖到资源管理器生成 Prefab。 - 场景中的模板节点可以删除。运行时生成的星星统一挂到
Playfield,与Player使用同一个坐标系。 - 读这三行,先预测省略第二行时会怎样。下一屏给出完整脚本。
const drop = instantiate(this.dropPrefab);
this.playfield.addChild(drop);
drop.setPosition(-120, 240, 0);
Prefab 作为模板可供重复实例化。一次下落结束后清理这次创建的节点,下一颗使用新的实例。创建和销毁节点
3. 把输入、计分与结算接起来
每帧用 速度 × dt 推进星星。到达接取线时只判一次,以玩家轨道和星星轨道是否一致决定分数,然后生成下一颗或结算。
- 到达接取线
- 比较轨道并计分
- 清理实例
- 下一颗或结算
- 新建
CatchGame.ts并复制下面完整脚本。把组件挂到 Canvas,在 Inspector 绑定 Playfield、Player、HUD 和 Drop Prefab。 - 打开每个 Button 的 Click Events,增加一项,将 Canvas 拖到 Target,Component 选择 CatchGame。Left、Right、Start 分别选择
moveLeft、moveRight、startOrRestart。 - 预览前先检查绑定。开始后一直留在左侧,应该得到 3 分。再开一局,按左、右、左、右、左接,应该得到 5 分。
完整脚本 CatchGame.ts
import {
_decorator, AudioSource, Component, instantiate, Label, Node, Prefab, Tween, tween, Vec3,
} from 'cc';
const { ccclass, property } = _decorator;
const laneX = [-120, 120];
const rounds = 5;
const startY = 240;
const catchY = -160;
const speed = 280;
@ccclass('CatchGame')
export class CatchGame extends Component {
@property(Node)
playfield: Node | null = null;
@property(Node)
player: Node | null = null;
@property(Label)
hud: Label | null = null;
@property(Prefab)
dropPrefab: Prefab | null = null;
@property(AudioSource)
catchSound: AudioSource | null = null;
private drop: Node | null = null;
private lane = 0;
private dropLane = 0;
private dropY = startY;
private attempt = 0;
private score = 0;
private playing = false;
startOrRestart() {
if (!this.playfield || !this.player || !this.hud || !this.dropPrefab) {
console.error('请在 Inspector 绑定 Playfield、Player、HUD 和 Drop Prefab。');
return;
}
this.removeDrop();
Tween.stopAllByTarget(this.hud.node);
this.hud.node.setScale(1, 1, 1);
this.score = 0;
this.attempt = 0;
this.playing = true;
this.moveLeft();
this.spawnDrop();
this.updateHud();
}
moveLeft() { this.moveTo(0); }
moveRight() { this.moveTo(1); }
update(dt: number) {
if (!this.playing || !this.drop) return;
this.dropY = Math.max(catchY, this.dropY - speed * dt);
this.drop.setPosition(laneX[this.dropLane], this.dropY, 0);
if (this.dropY > catchY) return;
if (this.lane === this.dropLane) {
this.score++;
this.catchSound?.play();
this.pulseHud();
}
this.removeDrop();
this.attempt++;
this.playing = this.attempt < rounds;
if (this.playing) this.spawnDrop();
this.updateHud();
}
private moveTo(lane: number) {
if (!this.playing) return;
this.lane = lane;
this.player?.setPosition(laneX[lane], catchY, 0);
}
private spawnDrop() {
if (!this.playfield || !this.dropPrefab) return;
this.dropLane = this.attempt % laneX.length;
this.dropY = startY;
const drop = instantiate(this.dropPrefab);
this.playfield.addChild(drop);
drop.setPosition(laneX[this.dropLane], this.dropY, 0);
this.drop = drop;
}
private removeDrop() {
if (!this.drop) return;
this.drop.active = false;
this.drop.destroy();
this.drop = null;
}
private updateHud() {
if (!this.hud) return;
this.hud.string = this.playing
? `第 ${this.attempt + 1} / ${rounds} 个 · 得分 ${this.score}`
: `结算 ${this.score} / ${rounds} · 点开始重开`;
}
private pulseHud() {
if (!this.hud) return;
const target = this.hud.node;
Tween.stopAllByTarget(target);
target.setScale(1, 1, 1);
tween(target).to(0.08, { scale: new Vec3(1.15, 1.15, 1) })
.to(0.12, { scale: new Vec3(1, 1, 1) }).start();
}
onDestroy() {
if (this.hud) Tween.stopAllByTarget(this.hud.node);
this.removeDrop();
}
}4. HUD、Tween 与音效
分数由回合代码修改,HUD 只读这个结果。每次接住后,pulseHud() 让 HUD 缩放两次,给玩家一个可见反馈。可选音效由 AudioSource 播放。
- 先在不绑定音效的情况下接中星星,检查分数和缩放。
- 要加声音,在 Canvas 添加 AudioSource,设置一个短音频 Clip,关闭 Play On Awake,再把组件拖到 Catch Sound。
- 接中后立刻重开,检查 HUD 是否恢复原比例。再试一次接空,确认不会触发得分反馈。
脚本在重开时停止 HUD 上一次缩放动画并归一比例,避免把上一局的显示状态带到新一局。
5. 资源路径与异步加载
小游戏先通过 Inspector 绑定 Drop Prefab,因而在点开始前就有资源引用。需要练习动态加载时,可以把素材放进 assets/resources/,从一个独立测试组件发起加载。
把同一素材复制到 assets/resources/stars/Drop.prefab 作为练习,路径从 resources 往下写,省略扩展名。下面是可在单独组件中尝试的片段,先导入 resources 和 Prefab。
resources.load('stars/Drop', Prefab, (error, prefab) => {
if (error) {
console.error('无法加载 Drop', error);
return;
}
console.log('资源已可用', prefab.name);
});
把路径改错一次,查看错误;改回后验证成功。若要把动态加载接入开始按钮,加载完成前应禁用开始或显示加载状态。动态加载资源
6. 构建 Web 并做一轮验收
- 保存
Main。打开「项目 → 构建发布」,选择 Web Mobile,核对 Main 在构建场景中且为启动场景。 - 执行构建,通过构建面板运行或使用本地静态服务器打开输出。打开开发者工具检查 Console 和 Network。
- 在构建结果中走完下方流程,再换成窄窗口检查文字与按钮布局。需要手机验证时,用设备可访问的预览地址打开。
7. 独立应用
现在改成「接金币得 1 分,接石头扣 1 分」。开新一局仍要清零。你会给下落物加什么状态,把判分放在哪一步,用哪两个场景验证?
8. 隔天回想
隔天先凭记忆回答。从点击「开始」到第一颗星结算,编辑器里的哪几个绑定会生效?你会在哪里打断点确认这个过程?
刷新会清空本页作答和验收勾选。可以收藏这一屏隔天再试。