渐进式编程课
Cocos Creator 目录
第 3 课2026.09.03

让一个可见节点以固定的局部单位每秒速率向右运动。

第 3 课:update与按时间移动

  • 日期:2026-09-03
  • 课程序号:第 3 课
  • 知识点:deltaTime 与局部坐标增量

用途

让一个可见节点以固定的局部单位每秒速率向右运动。

核心概念

  • start 做一次初始化,update(deltaTime) 逐帧更新,deltaTime 的单位是秒。
  • 新坐标必须基于当前坐标累加,直接 setPosition(speed * dt, ...) 只会反复放到起点附近。

最小代码或操作示例

ts
import { _decorator, Component } from "cc";
const { ccclass } = _decorator;
@ccclass("MoveNode")
export class MoveNode extends Component {
  start(): void {
    this.node.setPosition(0, 0, 0);
  }
  update(deltaTime: number): void {
    const p = this.node.position;
    this.node.setPosition(p.x + 40 * deltaTime, p.y, p.z);
  }
}

3~5 分钟练习

在 Creator 3.x 中挂到可见 Sprite 节点,避免同时挂其他位置脚本。预测运行约 2 秒的局部 X,再把 40 改成 -40。

参考答案

text
40 单位/秒、初始 X=0 时约 2 秒为 X=80;-40 时约为 -80,运动方向相反。父级缩放会影响观察到的世界位移。

与上一课的联系

上一课一次性设置局部变换;本课在现有位置上累计每帧位移。

参考资料