Spielerando

Gehzyklus

Rechnet aus, wo Füße, Körper und Arme einer gehenden Figur in jedem Moment eines Schritts sind, nach einer Regel und nicht aus gezeichneten Einzelbildern. Der Zyklus folgt der Strecke, die die Figur zurückgelegt hat, also bleibt ein Fuß am Boden bei jedem Tempo dort stehen, wo er steht.

Gras unter blauem Himmel, die Imkerin groß gezeichnet. Sie kommt von links, erst langsam, dann schnell, wird langsamer, bleibt mit beiden Füßen am Boden stehen und geht weiter und rechts hinaus. Unter jedem Fuß, der am Boden steht, leuchtet eine bernsteinfarbene Marke, und wo ein Fuß stand, bleibt eine Weile ein dunkler Fußabdruck. Die Abdrücke liegen gleichmäßig weit auseinander, egal wie schnell sie ist.
Ihre Schritte rücken so weit vor, wie sie geht, nicht nach der Uhr. Ob langsam oder schnell, jeder Fußabdruck ist eine saubere Marke im selben Abstand zum letzten, und ein stehender Fuß bewegt sich nicht, bis er sich hebt. Bleibt sie stehen, bleibt auch der Zyklus stehen.
Zwei Streifen Gras, in jedem geht die Imkerin im selben Tempo hinüber, neben jedem Streifen eine Lampe. Im oberen Streifen halten ihre Beine mit dem Körper Schritt, und ihre Fußabdrücke sind einzelne dunkle Marken; als sie fast hinüber ist, wird die Lampe grün, über der Zahl 0. Im unteren Streifen bewegen sich ihre Beine zu langsam für den Körper, also gleiten ihre Füße über das Gras und hinterlassen lange korallenrote Schmierspuren, und die Lampe wird rot mit einem Ausrufezeichen über 0,5.
Derselbe Gang, zweimal aufgezeichnet und geprüft. Oben folgt der Zyklus der Strecke, und die Prüfung findet kein Rutschen. Unten läuft der Zyklus nach der Uhr, in einem Takt, der nicht zu ihrem Tempo passt, also rutscht ein stehender Fuß in jedem Bild um 0,5 Pixel, und die Prüfung meldet das.

Wann du das brauchst

Für Figuren aus Einzelteilen, etwa ein Körper mit eigenen Beinen und Armen, für Strichfiguren und Roboter, und um die Einzelbilder eines Gangs zu erzeugen, ohne sie zu zeichnen. Es prüft auch einen aufgezeichneten Gang und nennt das Bild, in dem ein Fuß gerutscht ist. Es liefert Positionen: Wie die Teile gezeichnet werden, entscheidet dein Spiel, und das Rezept Arme und Beine ausrichten findet die Knie.

Das sagst du deiner KI

Nimm den Gehzyklus von Spielerando für die Beine und Arme meiner Figur, angetrieben von der Strecke, die sie zurücklegt. Zeichne 120 Bilder auf, in denen sie geht, langsamer wird und stehen bleibt, lass die Gang-Prüfung darüber laufen und zeig mir ihren Bericht Wort für Wort.

Der Knopf kopiert diesen Text zusammen mit dem getesteten Code unten, damit deine KI alles hat.

Einstellungen

Der Code

Getestetes TypeScript ohne fremde Teile. Kopier es in dein Spiel oder gib es deiner KI zusammen mit dem Text oben.

/* Walk cycle: where the feet, the body and the arms of a walking figure are at each moment of a
   step, worked out by a rule instead of drawn frame by frame. The cycle is driven by how far the
   figure has moved, not by the clock, so a foot on the ground stays where it stands: at any
   speed, when the figure slows down, and when it stops in the middle of a step.

   Usage:
     // every frame, with moved = how far the figure went this frame in the direction it faces, in pixels:
     phase = advance(phase, moved);
     const pose = walkPose(phase);
     pose.left.x; pose.left.height;     // the left foot: in front of or behind the hip, and above the ground
     pose.left.onGround;                // true while it carries the figure
     pose.right;                        // the same for the right foot, half a cycle later
     pose.bob;                          // how far the body is above its resting height right now
     pose.armSwing;                     // how far the left arm is swung forward, in radians; the right arm is the opposite

     // draw the hip at (figure.x, groundY - hipHeight - pose.bob), each foot at
     // (figure.x + foot.x * facing, groundY - foot.height), and a leg between them.
     // The arm and leg reach recipe gives you the knee.

     // to check that nothing slides, record what your game really did and ask:
     const report = checkWalk(samples);  // samples: [{ x: figure.x, phase }, ...], one a frame
     report.text;                        // "No foot slides." or the frame and how far

   The phase runs from 0 to 1 and starts again: one full cycle is one step with each foot. At 0
   the left foot has just come down in front. `stride` is how far the figure travels in that
   cycle. A foot on the ground moves backward under the hip exactly as fast as the figure moves
   forward, which is why it stays put.

   `groundShare` is the part of the cycle each foot spends on the ground. Above one half there
   are moments with both feet down, which reads as walking. Below one half there are moments
   with both feet in the air, which reads as running. `supportAt` tells you which it is.

   SPDX-License-Identifier: MIT
   Copyright (c) 2026 Spielerando, https://spielerando.com */

export const DEFAULTS = {
  /** How far the figure travels in one full cycle, a step with each foot, in pixels. */
  stride: 16,
  /** The part of the cycle each foot is on the ground: above 0.5 is a walk, below it a run. */
  groundShare: 0.6,
  /** How high a foot lifts while it swings forward, in pixels. */
  stepHeight: 3,
  /** How far the body rises above and sinks below its resting height, in pixels. */
  bob: 1,
  /** How far the arms swing forward and back, in radians. */
  armSwing: 0.5,
  /** How far a foot on the ground may move between two frames before checkWalk reports it, in pixels. */
  slideTolerance: 0.01,
};

export type WalkSettings = Partial<typeof DEFAULTS>;

export interface Foot {
  /** In front of the hip (positive) or behind it (negative), in pixels. */
  x: number;
  /** Above the ground, in pixels: 0 while it stands. */
  height: number;
  onGround: boolean;
}

export interface WalkPose {
  left: Foot;
  right: Foot;
  /** How far the body is above (positive) or below its resting height. */
  bob: number;
  /** How far the left arm is swung forward, in radians. The right arm is the opposite. */
  armSwing: number;
}

export type Support = "left" | "right" | "both" | "none";

/** A phase brought back into 0 to 1; a phase that is already there is not changed by a hair. */
function wrap(phase: number): number {
  const p = phase % 1;
  const q = p < 0 ? p + 1 : p;
  return q >= 1 ? 0 : q;
}

function settingsOf(settings: WalkSettings) {
  const s = { ...DEFAULTS, ...settings };
  if (!(s.stride > 0)) throw new Error(`The stride has to be more than 0 pixels, not ${s.stride}.`);
  if (!(s.groundShare > 0 && s.groundShare < 1)) throw new Error(`The ground share has to be between 0 and 1, not ${s.groundShare}: a foot is on the ground for part of the cycle, not all or none of it.`);
  return s;
}

/** The phase after the figure moved this far. Moving backward runs the cycle backward. */
export function advance(phase: number, moved: number, settings: WalkSettings = {}): number {
  return wrap(phase + moved / settingsOf(settings).stride);
}

/** One foot at a phase. The right foot is the left foot half a cycle later. */
export function footAt(phase: number, side: "left" | "right", settings: WalkSettings = {}): Foot {
  const { stride, groundShare, stepHeight } = settingsOf(settings);
  const p = wrap(phase + (side === "right" ? 0.5 : 0));
  const reach = (groundShare * stride) / 2;
  if (p < groundShare) {
    // on the ground: from in front of the hip to behind it, as far as the figure moves forward
    return { x: reach - p * stride, height: 0, onGround: true };
  }
  // in the air: forward again, slow at both ends so that it lifts off and lands softly
  const t = (p - groundShare) / (1 - groundShare);
  const eased = t * t * (3 - 2 * t);
  return { x: -reach + eased * 2 * reach, height: stepHeight * Math.sin(Math.PI * t), onGround: false };
}

/** Which feet carry the figure at a phase. */
export function supportAt(phase: number, settings: WalkSettings = {}): Support {
  const left = footAt(phase, "left", settings).onGround;
  const right = footAt(phase, "right", settings).onGround;
  return left && right ? "both" : left ? "left" : right ? "right" : "none";
}

/** The whole figure at a phase. */
export function walkPose(phase: number, settings: WalkSettings = {}): WalkPose {
  const { groundShare, bob, armSwing } = settingsOf(settings);
  const p = wrap(phase);
  return {
    left: footAt(p, "left", settings),
    right: footAt(p, "right", settings),
    // highest when a foot is straight under the hip, in the middle of its time on the ground; twice a cycle
    bob: bob * Math.cos(4 * Math.PI * (p - groundShare / 2)),
    // an arm swings with the leg of the other side: the left arm is back when the left foot comes down in front
    armSwing: -armSwing * Math.cos(2 * Math.PI * p),
  };
}

/** The phases of evenly spaced frames, for a sprite sheet of the cycle: `frames` pictures that loop. */
export function framePhases(frames: number): number[] {
  if (!Number.isInteger(frames) || frames < 2) throw new Error(`A cycle needs a whole number of frames, at least 2, not ${frames}.`);
  return Array.from({ length: frames }, (_, i) => i / frames);
}

export interface WalkSample {
  /** Where the figure is, in pixels along the ground. */
  x: number;
  /** The phase the figure was drawn with. */
  phase: number;
  /** -1 when the figure faces and walks to the left. Left out, it faces right. */
  facing?: number;
}

export interface WalkReport {
  ok: boolean;
  /** The farthest a foot moved over the ground from one frame to the next while it stood on it, in pixels. */
  worstSlide: number;
  /** Each time a foot slid more than the tolerance: the frame it slid in, counting from 1, which foot and how far. */
  slides: { frame: number; foot: "left" | "right"; distance: number }[];
  text: string;
}

/** Checks a recorded walk: a foot that stands on the ground in two frames in a row must be in the same place in both. */
export function checkWalk(samples: WalkSample[], settings: WalkSettings = {}): WalkReport {
  const { slideTolerance, groundShare, stride } = settingsOf(settings);
  const slides: WalkReport["slides"] = [];
  let worstSlide = 0;
  for (let i = 1; i < samples.length; i++) {
    const facing = samples[i].facing ?? 1;
    // how far the cycle ran between the two frames. The phases alone cannot tell three quarters forward
    // from one quarter backward, so take the reading nearest to what the distance moved says
    const expected = ((samples[i].x - samples[i - 1].x) * facing) / stride;
    const forward = wrap(samples[i].phase - samples[i - 1].phase);
    const ran = forward + Math.round(expected - forward);
    for (const foot of ["left", "right"] as const) {
      const before = wrap(samples[i - 1].phase + (foot === "right" ? 0.5 : 0));
      // the foot stood in the first frame; if it left the ground on the way, it stands in a new place by right
      if (before >= groundShare || before + ran < 0 || before + ran >= groundShare) continue;
      const place = (sample: WalkSample) => sample.x + footAt(sample.phase, foot, settings).x * (sample.facing ?? 1);
      const distance = Math.abs(place(samples[i]) - place(samples[i - 1]));
      worstSlide = Math.max(worstSlide, distance);
      if (distance > slideTolerance) slides.push({ frame: i + 1, foot, distance: Math.round(distance * 100) / 100 });
    }
  }
  const worst = [...slides].sort((a, b) => b.distance - a.distance)[0];
  const frames = new Set(slides.map((slide) => slide.frame)).size;
  const text =
    slides.length === 0
      ? `Checked ${samples.length} frames. No foot slides.`
      : `Checked ${samples.length} frames. A foot on the ground moves in ${frames} of them. The worst is frame ${worst.frame}: the ${worst.foot} foot stands on the ground and moves ${worst.distance} pixels. The cycle is not in step with how far the figure moves: advance the phase by the distance moved, not by the time passed.`;
  return { ok: slides.length === 0, worstSlide, slides, text };
}
Die Tests, die dieser Code besteht
import assert from "node:assert/strict";
import test from "node:test";
import { DEFAULTS, type Support, type WalkSample, advance, checkWalk, footAt, framePhases, supportAt, walkPose } from "./code.ts";

const close = (actual: number, expected: number, within = 1e-9) => assert.ok(Math.abs(actual - expected) <= within, `${actual} is not ${expected}`);
function random(seed: number) {
  let s = seed >>> 0;
  return () => {
    s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
    return s / 4294967296;
  };
}
const phases = Array.from({ length: 2000 }, (_, i) => i / 2000);

test("the phase follows the distance: one stride is one full cycle, and it wraps both ways", () => {
  assert.equal(DEFAULTS.stride, 16);
  close(advance(0, 4), 0.25);
  close(advance(0.9, 4), 0.15);
  close(advance(0.25, 16), 0.25);
  close(advance(0.1, -4), 0.85);
  close(advance(0, 5, { stride: 20 }), 0.25);
  assert.equal(advance(0.3, 0), 0.3);
});

test("a foot on the ground goes from in front of the hip to behind it, then swings forward in the air", () => {
  // with the defaults a foot is on the ground for 0.6 of the cycle and reaches 4.8 pixels each way
  const reach = (DEFAULTS.groundShare * DEFAULTS.stride) / 2;
  close(reach, 4.8);
  assert.deepEqual(footAt(0, "left"), { x: reach, height: 0, onGround: true });
  close(footAt(0.3, "left").x, 0);
  close(footAt(0.6 - 1e-12, "left").x, -reach, 1e-9);
  assert.equal(footAt(0.6, "left").onGround, false);
  close(footAt(0.6, "left").height, 0);
  close(footAt(0.8, "left").x, 0);
  close(footAt(0.8, "left").height, DEFAULTS.stepHeight);
  for (const p of phases) {
    const foot = footAt(p, "left");
    assert.ok(foot.height >= 0 && foot.height <= DEFAULTS.stepHeight + 1e-12, `height at ${p}`);
    assert.ok(Math.abs(foot.x) <= reach + 1e-12, `reach at ${p}`);
    assert.equal(foot.onGround, foot.height === 0 && p < 0.6, `on the ground at ${p}`);
  }
});

test("a foot never jumps: its path is one closed curve, and the right foot is the left half a cycle later", () => {
  for (const settings of [{}, { groundShare: 0.4 }, { groundShare: 0.5, stride: 30, stepHeight: 6 }]) {
    for (let i = 0; i < phases.length; i++) {
      const a = footAt(phases[i], "left", settings);
      const b = footAt(phases[(i + 1) % phases.length], "left", settings);
      assert.ok(Math.abs(a.x - b.x) < 0.05 && Math.abs(a.height - b.height) < 0.05, `from ${phases[i]}`);
      assert.deepEqual(footAt(phases[i], "right", settings), footAt(phases[i] + 0.5, "left", settings));
    }
  }
  assert.deepEqual(footAt(1.25, "left"), footAt(0.25, "left"));
  assert.deepEqual(footAt(-0.75, "left"), footAt(0.25, "left"));
});

/** A walk as a game would record it: the figure moves, and the phase follows the distance. */
function record(speeds: number[], settings = {}, facing = 1): WalkSample[] {
  let x = 100;
  let phase = 0.37;
  const samples: WalkSample[] = [{ x, phase, facing }];
  for (const speed of speeds) {
    x += speed * facing;
    phase = advance(phase, speed, settings);
    samples.push({ x, phase, facing });
  }
  return samples;
}

test("driven by distance, a foot on the ground does not move: at any speed, stopping, and backward", () => {
  const next = random(11);
  // speeds in pixels a frame: steady, slowing to a stop, standing, speeding up, backward, and at random
  const speeds = [
    ...Array.from({ length: 120 }, () => 1),
    ...Array.from({ length: 60 }, (_, i) => 1 - i / 60),
    ...Array.from({ length: 30 }, () => 0),
    ...Array.from({ length: 60 }, (_, i) => i / 20),
    ...Array.from({ length: 80 }, () => -0.7),
    ...Array.from({ length: 400 }, () => next() * 4 - 1),
  ];
  for (const settings of [{}, { groundShare: 0.4 }, { groundShare: 0.5 }, { stride: 40, groundShare: 0.7 }]) {
    for (const facing of [1, -1]) {
      const report = checkWalk(record(speeds, settings, facing), settings);
      assert.equal(report.ok, true, report.text);
      assert.ok(report.worstSlide < 1e-9, `the worst was ${report.worstSlide}`);
      assert.equal(report.text, "Checked 751 frames. No foot slides.");
    }
  }
});

test("planted: a cycle driven by the clock slides as soon as the speed does not match it", () => {
  // 60 frames a second, a cycle every half second, so the phase gains 1/30 a frame whatever the speed
  const byClock = (speed: number) => Array.from({ length: 121 }, (_, i) => ({ x: i * speed, phase: (i / 30) % 1 }));
  // 16 pixels a cycle and 30 frames a cycle: only 16/30 of a pixel a frame keeps the feet still
  const matched = checkWalk(byClock(16 / 30));
  assert.equal(matched.ok, true, matched.text);
  // at one pixel a frame the figure outruns its feet by 1 - 16/30 = 0.47 pixels every frame
  const fast = checkWalk(byClock(1));
  assert.equal(fast.ok, false);
  close(fast.worstSlide, 1 - 16 / 30, 1e-9);
  // in a walk some foot is on the ground from every frame to the next, so every one of the 120 steps slides
  assert.match(fast.text, /^Checked 121 frames\. A foot on the ground moves in 120 of them\. The worst is frame \d+: the (left|right) foot stands on the ground and moves 0\.47 pixels/);
  // standing still while the cycle keeps playing: the feet moonwalk by 0.53 pixels a frame
  const still = checkWalk(byClock(0));
  close(still.worstSlide, 16 / 30, 1e-9);
  assert.match(still.text, /moves 0\.53 pixels/);
  // walking backward while the cycle plays forward: the feet slide by the sum of both, 1.53 pixels a frame
  const moonwalk = checkWalk(byClock(-1));
  close(moonwalk.worstSlide, 1 + 16 / 30, 1e-9);
  assert.match(moonwalk.text, /moves 1\.53 pixels/);
  // a little slide can be allowed
  assert.equal(checkWalk(byClock(1), { slideTolerance: 0.5 }).ok, true);
});

test("a step taken between two frames is not called a slide", () => {
  // a fast figure: 13 pixels a frame is most of a cycle, so a foot lands in a new place each frame
  const report = checkWalk(record(Array.from({ length: 50 }, () => 13)));
  assert.equal(report.ok, true, report.text);
});

/** The moves between "which feet carry the figure" that a cycle may make. */
const MOVES: [Support, Support][] = [
  ["both", "left"], ["left", "both"], ["both", "right"], ["right", "both"],
  ["left", "none"], ["none", "right"], ["right", "none"], ["none", "left"],
  ["left", "right"], ["right", "left"],
];

test("which feet carry the figure follows the cycle: a walk has both down, a run has both in the air", () => {
  const order = (settings: object, backward = false) => {
    const seen: Support[] = [];
    const list = backward ? [...phases].reverse() : phases;
    for (const p of list) {
      const now = supportAt(p, settings);
      if (seen[seen.length - 1] !== now) seen.push(now);
    }
    return seen;
  };
  assert.deepEqual(order({}), ["both", "left", "both", "right"]);
  assert.deepEqual(order({ groundShare: 0.4 }), ["left", "none", "right", "none"]);
  assert.deepEqual(order({ groundShare: 0.5 }), ["left", "right"]);
  assert.deepEqual(order({}, true), ["right", "both", "left", "both"]);
  // every change, at every ground share and both ways round, is one of the moves listed
  for (let share = 0.05; share < 1; share += 0.05) {
    for (const backward of [false, true]) {
      const seen = order({ groundShare: share }, backward);
      seen.forEach((now, i) => {
        const before = seen[(i + seen.length - 1) % seen.length];
        assert.ok(MOVES.some(([a, b]) => a === before && b === now), `${before} to ${now} at ground share ${share}`);
      });
    }
  }
});

test("the body is highest over a standing foot, and the arms swing against the legs", () => {
  close(DEFAULTS.bob, 1);
  for (const p of phases) {
    const pose = walkPose(p);
    assert.ok(Math.abs(pose.bob) <= DEFAULTS.bob + 1e-12);
    assert.ok(Math.abs(pose.armSwing) <= DEFAULTS.armSwing + 1e-12);
    assert.deepEqual(pose.left, footAt(p, "left"));
    assert.deepEqual(pose.right, footAt(p, "right"));
    close(walkPose(p + 0.5).bob, pose.bob, 1e-9);
    close(walkPose(p + 0.5).armSwing, -pose.armSwing, 1e-9);
  }
  // the left foot is under the hip at 0.3, the right at 0.8: the body is at its highest there
  close(footAt(0.3, "left").x, 0);
  close(walkPose(0.3).bob, 1);
  close(walkPose(0.8).bob, 1);
  close(walkPose(0.05).bob, -1);
  // the left foot comes down in front at 0: the left arm is all the way back, and forward half a cycle later
  close(walkPose(0).armSwing, -DEFAULTS.armSwing);
  close(walkPose(0.5).armSwing, DEFAULTS.armSwing);
  assert.deepEqual(walkPose(1.25), walkPose(0.25));
});

test("evenly spaced frames make a loop: one more step after the last frame is the first frame again", () => {
  assert.deepEqual(framePhases(4), [0, 0.25, 0.5, 0.75]);
  for (const frames of [2, 4, 6, 8, 12]) {
    const list = framePhases(frames);
    assert.equal(list.length, frames);
    const after = walkPose(list[frames - 1] + 1 / frames);
    const first = walkPose(list[0]);
    for (const foot of ["left", "right"] as const) {
      close(after[foot].x, first[foot].x);
      close(after[foot].height, first[foot].height);
      assert.equal(after[foot].onGround, first[foot].onGround);
    }
    close(after.bob, first.bob);
    close(after.armSwing, first.armSwing);
    // and the frames are evenly spaced, so the loop plays at one pace
    for (let i = 1; i < frames; i++) close(list[i] - list[i - 1], 1 / frames);
  }
  for (const bad of [1, 0, 2.5]) assert.throws(() => framePhases(bad), /whole number of frames, at least 2/);
});

test("settings that make no walk are refused", () => {
  for (const stride of [0, -5, Number.NaN]) assert.throws(() => advance(0, 1, { stride }), /stride has to be more than 0/);
  for (const groundShare of [0, 1, 1.2, -0.1]) assert.throws(() => walkPose(0, { groundShare }), /ground share has to be between 0 and 1/);
});

Häufige Fragen

warum rutschen die füße meiner figur über den boden

Die Laufanimation läuft nach der Uhr, während sich die Figur in ihrem eigenen Tempo bewegt, und beides passt nicht zusammen. Treib die Animation stattdessen mit der zurückgelegten Strecke an, dann bleibt ein Fuß am Boden bei jedem Tempo stehen.

wie animiere ich einen gang ohne einzelbilder zu zeichnen

Lass eine Regel die Füße setzen: Am Boden wandert ein Fuß so schnell unter der Hüfte nach hinten, wie der Körper nach vorn geht, und in der Luft schwingt er nach vorn. Zeichne die Beine zwischen Hüfte und Fuß und lass den Körper leicht steigen und sinken.

wie wird aus einem gang ein lauf

Verkürze die Zeit, die jeder Fuß am Boden ist, auf weniger als den halben Zyklus und verlängere den Schritt. Dann gibt es Momente mit beiden Füßen in der Luft, und genau das lässt es wie Rennen wirken.

War diese Seite hilfreich?

Ein Klick, ohne Konto. So sehen wir, welche Seiten helfen.

Nächster Schritt

Code-Rezept

Arme und Beine ausrichten

Du sagst, wohin Hand oder Fuß soll, und es berechnet, wo Ellbogen oder Knie hinkommen. Füße bleiben auf Stufen, Hände greifen nach Kanten, und ein Roboterarm folgt der Maus.