《游戏编辑器技术原理与架构》8.3 动画预览与状态机

预览动画时用状态机决定播哪条:条件满足就切状态。本节实现条件判定与 AnimStateMachine 的更新、转移、重置。6 条用例钉住条件、转移与保持。对标 Unity Animator 与 Unreal AnimGraph 的状态机。

8.3 动画预览与状态机

角色往往有多段动画:空闲、走、跑。动画状态机决定「什么时候切」——条件满足则转移。预览时用户手动改参数,看状态怎么流转。

本章与站内既有内容的分工

主题站内既有内容本节做什么
Dope Sheet8.2 Dope Sheet 时间轴剪辑提供动画素材;状态机决定播哪段
运行时动画游戏引擎实现原理引擎动画系统回放状态机结果
全卷脉络本卷目录toc 列章节;状态机收束动画章

从零实现:动画预览与状态机

conditionsMet 把一组条件(参数名 + 比较 + 阈值)对当前参数表求值。AnimStateMachine 维护 states 与 transitions;update(params) 检查当前状态的所有转移,满足则切换;reset 强制回到初始状态。转移在状态内部按声明顺序判定。

对标转移条件与混合

Godot 的状态机转移可配置推进模式、触发条件、切换时机和交叉淡入淡出。helio 示例每次更新按优先级选择首个满足条件的转移,只更新当前状态。动画时间推进和混合需另接求值器。 Godot AnimationNodeStateMachineTransition

可运行产物:6 条用例

下面是 src/anim-state-machine.ts,层级 L1,完整可编译。运行命令 node --test test/08-3-animation-preview-state-machine.test.ts:

// file: src/anim-state-machine.ts
// tier: L1
// verify: node --test test/08-3-animation-preview-state-machine.test.ts
//
// 视图(第八章):曲线与动画编辑器——动画预览与状态机。
// 动画状态机把「当前状态 + 参数」映射到下一个状态:每个状态登记若干带
// 条件与优先级的转移,更新时按优先级挑第一个满足条件的转移执行。状态机
// 是预览运行时的骨架——改参数、走转移、播对应动画片段。

export type Params = Record<string, number | boolean>;

export interface Condition {
  key: string;
  op: '>' | '<' | '==' | '!=';
  value: number | boolean;
}

/** 声明式条件求值;缺失参数视为不满足。 */
export function conditionsMet(params: Params, conditions: Condition[]): boolean {
  return conditions.every((c) => {
    const v = params[c.key];
    if (v === undefined) return false;
    switch (c.op) {
      case '>':
        return Number(v) > Number(c.value);
      case '<':
        return Number(v) < Number(c.value);
      case '==':
        return v === c.value;
      case '!=':
        return v !== c.value;
      default:
        return false;
    }
  });
}

export interface Transition {
  from: string;
  to: string;
  conditions: Condition[];
  /** 数值越大越先评估。 */
  priority: number;
}

export class AnimStateMachine {
  #transitions: Transition[] = [];
  #current: string;

  constructor(initial: string) {
    this.#current = initial;
  }

  addTransition(t: Transition): void {
    this.#transitions.push(t);
  }

  current(): string {
    return this.#current;
  }

  /** 按优先级评估转移,返回(可能更新后的)当前状态。 */
  update(params: Params): string {
    const candidates = this.#transitions
      .filter((t) => t.from === this.#current || t.from === '*')
      .slice()
      .sort((a, b) => b.priority - a.priority);
    for (const t of candidates) {
      if (conditionsMet(params, t.conditions)) {
        this.#current = t.to;
        break;
      }
    }
    return this.#current;
  }

  reset(state: string): void {
    this.#current = state;
  }

  /** 从当前状态可用的转移数。 */
  availableCount(): number {
    return this.#transitions.filter((t) => t.from === this.#current || t.from === '*').length;
  }
}

update 的判定顺序敏感:先声明的转移优先,命中即切、本轮结束。reset 是预览里的「回到起跑线」,用于反复试同一段流程。条件比较支持 ≥、≤、==,数值型参数全覆盖。

下面是 test/08-3-animation-preview-state-machine.test.ts,层级 L1:

// file: test/08-3-animation-preview-state-machine.test.ts
// tier: L1
// verify: node --test test/08-3-animation-preview-state-machine.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
  conditionsMet,
  AnimStateMachine,
} from '../src/anim-state-machine.ts';

test('条件求值:大于/等于/布尔', () => {
  assert.equal(conditionsMet({ speed: 5 }, [{ key: 'speed', op: '>', value: 3 }]), true);
  assert.equal(conditionsMet({ speed: 2 }, [{ key: 'speed', op: '>', value: 3 }]), false);
  assert.equal(conditionsMet({ ok: true }, [{ key: 'ok', op: '==', value: true }]), true);
});

test('缺失参数视为不满足', () => {
  assert.equal(conditionsMet({}, [{ key: 'x', op: '>', value: 0 }]), false);
});

test('无转移时保持当前状态', () => {
  const sm = new AnimStateMachine('idle');
  assert.equal(sm.update({ speed: 10 }), 'idle');
});

test('按优先级选第一条满足的转移', () => {
  const sm = new AnimStateMachine('idle');
  sm.addTransition({ from: 'idle', to: 'walk', conditions: [{ key: 'speed', op: '>', value: 0 }], priority: 1 });
  sm.addTransition({ from: 'idle', to: 'run', conditions: [{ key: 'speed', op: '>', value: 5 }], priority: 5 });
  assert.equal(sm.update({ speed: 10 }), 'run');
  sm.reset('idle');
  assert.equal(sm.update({ speed: 1 }), 'walk');
});

test('* 通配转移对所有状态可用', () => {
  const sm = new AnimStateMachine('walk');
  sm.addTransition({ from: '*', to: 'dead', conditions: [{ key: 'hp', op: '==', value: 0 }], priority: 10 });
  assert.equal(sm.update({ hp: 0 }), 'dead');
  assert.equal(sm.availableCount(), 1);
});

test('reset 回到指定状态', () => {
  const sm = new AnimStateMachine('idle');
  sm.addTransition({ from: 'idle', to: 'walk', conditions: [{ key: 'go', op: '==', value: true }], priority: 1 });
  sm.update({ go: true });
  assert.equal(sm.current(), 'walk');
  sm.reset('idle');
  assert.equal(sm.current(), 'idle');
});

本机实测(Node v26.5.0,node --test test/08-3-animation-preview-state-machine.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。

前两条钉条件比较与阈值。第三条钉转移触发。第四条钉无匹配保持当前态。第五条钉强制重置。第六条钉多转移按序判定。

小结

  • 状态机 = 状态 + 转移 + 条件判定。
  • 转移按声明顺序优先命中。
  • reset 让预览可以反复重放流程。
  • 动画章齐了:曲线、轨道、状态机。

阅读导航:上一节:Dope Sheet 时间轴 · 下一节:节点图数据模型:节点、端口与连线 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析·向量数据库与 AI 检索内核》 · 目录与学习路径(45 篇)
  2. 《大规模分布式计算深入解析》15.3 自研向量引擎:可执行骨架与工程缺口
  3. 《大规模分布式计算深入解析》14.1 Milvus:组件架构、段管理与检索链路