31. 2D Fighting Game Part 2: Attacks, Hitboxes and the Scene Graph

In chapter 30 Hayate and Jin learned to walk, jump, crouch and push against each other.
Now they fight.
This chapter gives them five moves, decides when a move hits, what a hit does to the victim, and how the game shows it: sparks, a freeze on impact, a shaking screen, health bars and a combo counter.
It also builds a small 2D scene graph, the 2D version of chapter 14's glTF node hierarchy, for the parts that move on their own: the headband tails, the dizzy stars, the shadow and the effects.

There are no new OpenGL functions in this chapter.
Fighting games are about time, measured in frames, and most of the chapter is about getting one frame right.
The code is long, so I show the parts where a decision was made and explain why; the rest is in the download.

31.1 What we're building

Two players on one keyboard, in a training dojo: every hit is logged, and a K.O. restarts the round after three seconds.

The dojo at 1280 by 720. Hayate in white lands a kick on Jin in blue; a white and orange spark sits on Jin&

The clip is a scripted fight: a punch → punch combo, a blocked kick, a jump kick → sweep combo, Jin's jump kick beating a crouching guard, Jin's punch blocked by a crouching guard, and finally a kick that knocks Jin out.

The controls:

1P 2P
walk A D ← →
jump (+ direction) W ↑
crouch S ↓
punch F K or keypad 1
kick G L or keypad 2

  • Crouch + punch is a crouching punch, crouch + kick a sweep (low, knocks down), punch or kick in the air a jump kick (high)
  • Guard: hold away from the opponent; down-away guards crouching
  • F1 shows the boxes (hurt blue, hit red, push green, sockets yellow) and each fighter's state; Esc quits
  • Gamepads: the first is 1P, the second 2P; d-pad or left stick, A or X punch, B or Y kick

Like every game chapter, nothing outside games/fighter/ changes.
From chapter 30, the changes are:

  • src/moves.hh, src/moves.cc (new): the move table, the frame data
  • src/input_buffer.hh (new): remembers button presses for 8 frames
  • src/frame_data.hh, src/frame_data.cc (new): loads the per-frame hurt boxes, hit boxes and sockets
  • src/scene_graph.hh, src/scene_graph.cc (new): Affine2, Node, toSprite
  • src/effects.hh, src/effects.cc (new): sparks and dust as scene-graph nodes
  • src/controls.hh, src/controls.cc: punch and kick buttons, gamepad button edges
  • src/fighter.hh, src/fighter.cc: attack, hit stun, block stun, knockdown, get-up and KO states, guarding, taking hits, the parts tree
  • src/fight_scene.hh, src/fight_scene.cc: hit detection, hit stop, screen shake, health bars, the combo counter, the KO and the training reset
  • src/game.hh, src/main.cc: the effects sheet and the box data
  • assets/fighter.boxes, assets/effects.png, assets/effects.atlas (new), assets/LICENSE.txt, README.md (the finished files are in the chapter's ZIP and in ch31/ of the assets ZIP)

The four new sources join the executable:

add_executable(fighter
  src/main.cc
  src/controls.cc
  src/effects.cc
  src/fighter.cc
  src/fight_scene.cc
  src/frame_data.cc
  src/moves.cc
  src/scene_graph.cc)

31.2 Moves are frame data

Startup, active and recovery

A punch isn't an animation that happens to hurt.
It's a schedule, counted in frames of 1/60 s from the step the button was read:

  • Startup: the arm is on its way; nothing can be hit yet
  • Active: the fist is out; this is the only time the move has a hit box
  • Recovery: the arm comes back; the attacker can't do anything else and is open to a counterattack

A row of 16 frame cells for the punch: frames 1 to 4 are startup and show sprite punch0, frames 5 to 7 are active and show punch1, the only frames with a hit box, frames 8 to 15 are recovery with punch2, and frame 16 is IDLE again. An arrow marks frame 1 as the step the button was read

This is what fighting-game players call frame data, and in this game it really is data: one row per move.

The move table

// 技の性能表(フレームデータ):発生・持続・硬直、ダメージ、のけぞり、ガード硬直、ヒットストップ、ノックバック
// The move table (frame data): startup, active, recovery, damage, hit stun, block stun, hit stop, knockback
#pragma once

enum class MoveId { Punch, Kick, CrouchPunch, Sweep, JumpKick, Count };

// どうガードするか:中段 = 立ちでもしゃがみでも、下段 = しゃがみだけ、上段(飛び込み) = 立ちだけ
// How it must be blocked: mid = standing or crouching, low = crouching only, high (jump-ins) = standing only
enum class AttackHeight { Mid, Low, High };

struct MoveData {
  const char *name;
  const char *frames[3];   // コマ:発生・持続・硬直 / sprite frames: startup, active, recovery
  int startup, active, recovery; // フレーム数(1/60秒) / frames (1/60 s)
  int damage;
  int hitstun, blockstun;  // 当たった・ガードされた相手が動けないフレーム / frames the opponent cannot act
  int hitstop;             // 当たった瞬間に二人とも止まるフレーム / frames both freeze on contact
  float knockback;         // 相手を押す速さ(ピクセル毎秒、摩擦で減る) / push speed (px/s, decays with friction)
  AttackHeight height;
  bool knockdown;          // 当たるとダウン / knocks down on hit
  bool air;                // 空中技(着地で終わる) / an air move (ends on landing)

  int total() const { return startup + active + recovery; }
};

const MoveData &moveData(MoveId id);

frames names the three sprites of the move, one per phase.
hitstun and blockstun are how long the victim can't act after being hit or after blocking; hitstop is the freeze on contact (31.8); knockback is a speed in pixels per second that friction eats up; height decides how the move must be blocked (31.7).
The table itself, with the comment that works out the frame advantage, which is the next section:

// 有利不利(当てた後どちらが先に動けるか)= 相手の硬直 −(持続の残り + 自分の硬直)。最初の持続フレームで当てた場合:
//   突き:ヒット 17 − (2 + 8) = +7、ガード 10 − 10 = ±0(ヒットなら突き → 突きがつながる:7 ≥ 発生4 + 3)
//   蹴り:ヒット 19 − (3 + 16) = ±0、ガード 13 − 19 = −6(突きの発生4で反撃される)
//   足払い:ダウンを取る、ガード 12 − (2 + 20) = −10(大きな隙)
// つながる条件は 有利 ≥ 発生 + 3:技が終わるステップはIdleに戻るだけ、当たるのは発生の次のフレーム、
// 相手は硬直が0になったステップでもう自由
// Frame advantage (who acts first afterwards) = the opponent's stun − (the rest of the active frames + own recovery).
// Hitting on the first active frame:
//   punch: hit 17 − (2 + 8) = +7, block 10 − 10 = ±0 (on hit punch → punch links: 7 ≥ startup 4 + 3)
//   kick: hit 19 − (3 + 16) = ±0, block 13 − 19 = −6 (punishable by the 4-frame punch)
//   sweep: knocks down; block 12 − (2 + 20) = −10 (a big opening)
// A move links when the advantage ≥ its startup + 3: the step a move ends only returns to Idle, the hit comes on the
// frame after the startup, and the victim is free on the step its stun reaches 0
constexpr MoveData kMoves[] = {
  // 名前 / name   コマ / frames                          発生 持続 硬直  ダメ のけぞり ガード 停止 押し
  {"PUNCH", {"punch0", "punch1", "punch2"},               4, 3, 8,     6, 17, 10, 7, 140.0f, AttackHeight::Mid, false, false},
  {"KICK", {"kick0", "kick1", "kick2"},                   8, 4, 16,    12, 19, 13, 11, 230.0f, AttackHeight::Mid, false, false},
  {"C.PUNCH", {"cpunch0", "cpunch1", "cpunch2"},          4, 3, 8,     5, 15, 9, 7, 120.0f, AttackHeight::Mid, false, false},
  {"SWEEP", {"sweep0", "sweep1", "sweep2"},               7, 3, 20,    10, 0, 12, 10, 120.0f, AttackHeight::Low, true, false},
  // 飛び蹴り:持続は着地まで(硬直0、着地の硬直は別) / jump kick: active until landing (recovery 0; landing
  // recovery comes separately)
  {"J.KICK", {"jkick0", "jkick1", "jkick1"},              6, 40, 0,    10, 18, 12, 10, 160.0f, AttackHeight::High, false, true},
};

Here are the same numbers as a table (frames at 60 Hz, knockback in px/s):

Move Input Startup Active Recovery Damage Hit stun Block stun Hit stop Knockback Height
PUNCH P 4 3 8 6 17 10 7 140 mid
KICK K 8 4 16 12 19 13 11 230 mid
C.PUNCH down + P 4 3 8 5 15 9 7 120 mid
SWEEP down + K 7 3 20 10 knockdown 12 10 120 low
J.KICK P or K in the air 6 until landing 0, then 4 landing 10 18 12 10 160 high

The jump kick's 40 active frames are just "longer than any jump": an air move ends when the fighter lands (onLanding turns it into the 4-frame Land state).
Its third sprite name is never used, because it never reaches recovery.

The timeline picks the sprite

In chapter 30 the Animator played clips at a frame rate.
That's still how idle, walk and win animate, but not moves.
A move's sprite comes from its phase, and the phase comes from the frame counter:

// 技を始める。押したステップが発生の1フレーム目 / starts a move; the step of the press is startup frame 1
void Fighter::startMove(MoveId id) {
  moveId = id;
  move = &moveData(id);
  moveHit = false;
  state = FighterState::Attack;
  stateTime = 1;
  if (!move->air) velocity.x = 0.0f;
}

// バッファにある突き・蹴りを技にする(しゃがみ中は下段の技) / turns a buffered punch or kick into a move (crouching
// moves while crouching)
bool Fighter::tryMoves(bool crouching) {
  if (buffer.take(Button::Kick)) {
    startMove(crouching ? MoveId::Sweep : MoveId::Kick);
    return true;
  }
  if (buffer.take(Button::Punch)) {
    startMove(crouching ? MoveId::CrouchPunch : MoveId::Punch);
    return true;
  }
  return false;
}

MovePhase Fighter::phase() const {
  if (state != FighterState::Attack || !move) return MovePhase::None;
  if (stateTime <= move->startup) return MovePhase::Startup;
  if (stateTime <= move->startup + move->active) return MovePhase::Active;
  return MovePhase::Recovery;
}

The press step is frame 1: startMove sets stateTime = 1 itself, because update has already incremented it before the state switch runs.
tryMoves reads the input buffer (31.4), and a crouching fighter gets the crouching versions of both buttons.
In chooseFrame, the Attack state doesn't touch the animator at all:

  case FighterState::Attack: {
    // 技のコマは時間(フレームデータ)で決まる。アニメーションのfpsではない / a move's frame comes from its timeline
    // (the frame data), not from an animation fps
    MovePhase p = phase();
    const char *frameName = move->frames[p == MovePhase::Startup ? 0 : p == MovePhase::Active ? 1 : 2];
    frame = findFrame(sheet, frameName);
    return;
  }

Why not play a "punch" clip at some fps?
Because then the art and the rules would be two clocks that can drift.
If someone changes the punch's startup from 4 to 5, the sprite has to change one frame later too, and with this design it does without anyone touching an animation.
The rule "the hit box exists in the active frames" and the rule "the fist is out in the active frames" become the same rule.
(Changing the table also never needs new art: the move just holds each sprite longer or shorter.)

A ground move ends after its total frames:

    // 地上技は全体フレームが終わったら自由に。空中技は着地で終わる(onLanding) / a ground move frees the fighter
    // after its total frames; an air move ends on landing (onLanding)
    if (!move->air && stateTime > move->total()) {
      move = nullptr;
      setState(c.down ? FighterState::Crouch : FighterState::Idle);
    }
    break;

Look at the step on which this runs: stateTime is 16 for the punch.
The fighter becomes Idle in that step, but the Idle branch (and with it tryMoves) only runs on the next one.
So a buffered move starts on frame 17, not on frame 16, as the picture above shows.
That one step matters in the next section.

31.3 Frame advantage and links

After a punch hits, who can act first, the attacker or the victim?
The difference is the frame advantage:

advantage=stun−(remaining active frames+recovery)

Counting from a hit on the first active frame, as the comment in moves.cc does:

Move On hit On block
PUNCH 17 − (2 + 8) = +7 10 − (2 + 8) = 0
KICK 19 − (3 + 16) = 0 13 − (3 + 16) = −6
C.PUNCH 15 − (2 + 8) = +5 9 − (2 + 8) = −1
SWEEP knockdown 12 − (2 + 20) = −10

Positive means the attacker is free first.
A blocked kick at −6 is punishable: the defender is free 6 frames before the kicker, enough for a 4-frame punch to come out and hit.
(For the sweep, count carefully: with three active frames, two remain after the first one, so a blocked sweep is 12 − (2 + 20) = −10, as the comment in moves.cc works out.)

Hit stop doesn't change any of this, because it freezes both fighters for the same number of steps.

A link: punch → punch

If the advantage is big enough, the attacker's next move hits before the victim leaves hit stun: a link, a combo made of two separate moves.
On paper, +7 is plenty for a punch with 4 startup frames.
In the code, the punch's hit stun of 17 is the smallest value that works, and 16 is one frame short.
Here is the exact count, step by step after the first punch's hit stop:

A timeline of 17 steps after a 7-step hit stop. Hayate: punch frames 6 and 7 active, 8 to 15 recovery, 16 back to IDLE on step 11, then the buffered second punch with startup frames 1 to 4 on steps 12 to 15 and its first active frame on step 16. Jin with hit stun 17 counts down 16 to 1 and is still in HITSTUN on step 16, so the hit is combo 2. With hit stun 16 he counts down 15 to 1 and is already IDLE on step 16, so the hit is combo 1

Three edges each cost one frame of the +7:

  1. The step a move ends, the fighter only returns to Idle (31.2); the buffered punch starts one step later.
  2. Startup 4 means four frames before the fist is out: the second punch hits on its fifth frame.
  3. On the step Jin's stun reaches 0, his state is Idle before the hits are checked, so the last step he can be comboed is the one with 1 left.

So in this code a move links when the advantage is at least its startup + 3: 7 ≥ 4 + 3 links, 6 doesn't.
The off-by-one on "which step is frame 1" is the classic bug in this kind of code, and it was the bug here too: with hit stun 16 the second punch became active on the very step the stun ended.
I checked both numbers in the game itself rather than trusting the arithmetic; with the clip's script the log shows the two punches 23 steps apart (7 frozen steps, then 16 more):

step 86: HAYATE PUNCH -> JIN hit, hp 94, combo 1, hit stop 7
step 109: HAYATE PUNCH -> JIN hit, hp 88, combo 2, hit stop 7

With hit stun 16 the second line becomes combo 1: same step, but Jin was already free.
The crouching punch (+5) doesn't link into itself, which the formula also predicts: 5 < 4 + 3.
The blocked kick is a punish with one frame to spare: the defender's punch hits on step 18 after the hit stop while the kick recovers until step 19, but only up close: the guard pushes the defender back about 11 px, and from the kick's longest range the punch no longer reaches.

The jump kick → sweep in the clip is a combo for a different reason: the jump kick hits late in the jump, so Hayate lands only 2 steps after the hit stop.
Then come 4 landing frames, the Idle step and the sweep's 7 startup frames, and the sweep hits on step 2 + 12 = 14, well inside the 17 steps Jin spends in hit stun (18 − 1, edge 3 again).

31.4 The input buffer

The link above needs the second press to come out on exactly step 12.
Nobody presses a button on an exact 1/60 s step, so games remember presses for a short while: the input buffer.
First, Controls now carries buttons as "pressed this step", while directions stay "held":

// 1ステップ分の入力。方向は押している間、ボタンは押した瞬間だけ。ファイターはこれだけを見る
// One step of input. Directions are "held", buttons are "pressed this step". The fighter only sees this
struct Controls {
  bool left = false, right = false, up = false, down = false;
  bool punch = false, kick = false;
};

The buffer stores the age of the last press of each button:

// 入力バッファ:ボタンを押してから数フレームの間、その入力を覚えておく。硬直が解けた瞬間に技が出る
// The input buffer: remembers a button press for a few frames, so a move comes out the moment recovery ends
#pragma once

#include "controls.hh"

enum class Button { Punch, Kick };

class InputBuffer {
public:
  // 何フレーム前の押下まで有効か(60 Hzで約0.13秒) / how old a press may be (about 0.13 s at 60 Hz)
  static constexpr int kWindow = 8;

  // 毎ステップ一回(ヒットストップ中も):押した瞬間を年齢0として記録し、ほかは1つ年を取る
  // Once per step (also during hit stop): a fresh press gets age 0, everything else gets one step older
  void record(const Controls &c) {
    for (int &a : age) a = a < kNone ? a + 1 : kNone;
    if (c.punch) age[0] = 0;
    if (c.kick) age[1] = 0;
  }
  // 窓の中に押下があれば使い切ってtrue(一回の押下で技は一つ) / true (and used up) if there is a press inside the
  // window: one press, one move
  bool take(Button b) {
    int &a = age[static_cast<int>(b)];
    if (a > kWindow) return false;
    a = kNone;
    return true;
  }
  bool waiting(Button b) const { return age[static_cast<int>(b)] <= kWindow; }
  void clear() { age[0] = age[1] = kNone; }

private:
  static constexpr int kNone = 1000;
  int age[2] = {kNone, kNone};
};

A press may be up to 8 frames old (0.13 s) when the fighter becomes free.
take consumes it: one press, one move, so a press during recovery doesn't fire twice.
Pressing the second punch anywhere from 8 steps before step 12 up to step 12 itself gives the same, frame-perfect link, and the clip's second press does come 7 steps early (it's a buffered input, not a lucky one).
Every move goes through the buffer, human or (in chapter 32) the CPU, so both play by the same timing.

The buffer is recorded at the top of every step, also during hit stop (31.8).
A press made while everything is frozen is still there when things move again.

GLFW gamepads only report button states, not presses, so readControls makes the presses itself by comparing with the last step (GamepadEdges, one per player):

  // GLFWのゲームパッドは状態だけ:押した瞬間は前のステップと比べて作る / GLFW gamepads only give states: presses
  // come from comparing with the last step
  bool punch = down(GLFW_GAMEPAD_BUTTON_A) || down(GLFW_GAMEPAD_BUTTON_X);
  bool kick = down(GLFW_GAMEPAD_BUTTON_B) || down(GLFW_GAMEPAD_BUTTON_Y);
  c.punch |= punch && !edges.punch;
  c.kick |= kick && !edges.kick;
  edges = {punch, kick};

31.5 Hit boxes and hurt boxes as data

A fighter has three kinds of boxes:

  • Hurt boxes (blue): where the fighter can be hit; three per frame (head, torso, legs), plus one along an extended limb during an attack, so a whiffed kick can be hit in the leg
  • Hit box (red): where the move hurts; one, only in active-frame sprites, around the fist or the foot
  • Push box (green, from chapter 30): keeps the bodies apart; it has nothing to do with hits

Hand-placing boxes over 38 frames is slow, and worse, boxes drift away from the art every time someone edits a pose.
Our frames are already generated from a skeleton by my own script (chapter 30), so the same script writes the boxes from the same poses: the head box from the head joint, the hit box around the fist joint of punch1, and so on.
The art and the boxes can't disagree, because both are made from one pose.

Three frames of Hayate, punch1, kick1 and sweep1, with their box data drawn over them: blue hurt boxes for head, torso and legs plus one along the extended arm or leg, a red hit box around the fist or the foot, yellow socket circles at the head, the headband knot, the fist and the foot, and a white cross at the feet

The file is plain text, relative to the feet, facing right, y down:

# 当たり判定のデータ(作者の自作スクリプトが骨格から作る) / hit and hurt box data, made from the skeleton by
# the author's own script. Pixels relative to the feet pivot, facing right, y down.
#   hurt <frame> x y w h    食らい判定 / where the fighter can be hit
#   hit <frame> x y w h     攻撃判定(有効フレームのコマ) / attack box (active frames)
#   socket <frame> <name> x y   部品・エフェクトの取り付け位置 / where parts and effects attach

and the punch's active frame:

hurt punch1 6 -89 16 16
hurt punch1 -6 -81 26 45
hurt punch1 -19 -48 41 50
hurt punch1 22 -74 26 10
hit punch1 37 -75 14 10
socket punch1 head 14 -81
socket punch1 knot 5 -85
socket punch1 fist 44 -70
socket punch1 foot 22 -2

Sockets are named points (head, knot, fist, foot) where parts attach; the scene graph uses them in 31.10.
One file serves both fighters, because Jin is a palette swap of Hayate with the same frame names and indices.
FrameData loads it into a vector indexed like the sprite sheet, so data[frame] is the boxes of whatever sprite is on screen:

// 足元からの位置、右向き、y下向き(ピクセル) / relative to the feet, facing right, y down (pixels)
struct FrameBoxes {
  std::vector<Rect> hurt;  // 食らい判定(ここに当たるとやられる) / hurt boxes (getting hit here hurts)
  std::optional<Rect> hit; // 攻撃判定(持続フレームのコマだけ) / the attack box (active-frame sprites only)
  Vec2 head, knot, fist, foot; // ソケット:頭・鉢巻の結び目・近い拳・近い足 / sockets: head, headband knot, near fist,
                               // near foot
};

class FrameData {
public:
  // 行の形式 / line format:  hurt <frame> x y w h | hit <frame> x y w h | socket <frame> <name> x y | # comment
  // コマの名前はsheetで引く(sheetのコマ番号で並ぶ) / frame names are looked up in `sheet` (indexed like the sheet)
  static std::optional<FrameData> load(const std::string &path, const SpriteSheet &sheet);
  const FrameBoxes &operator[](int frame) const { return frames[static_cast<size_t>(frame)]; }

private:
  std::vector<FrameBoxes> frames;
};

// 右向きの箱を、向き(±1)と足元の位置でワールドへ / a facing-right box into the world for a facing (±1) and the feet
Rect toWorld(const Rect &local, Vec2 feet, float facing);

load reports errors as file:line (an unknown frame name, a missing number) and returns std::nullopt, like the engine's loaders; main gives up if it fails.
The boxes are stored facing right; a fighter facing left mirrors them around the feet:

Rect toWorld(const Rect &local, Vec2 feet, float facing) {
  // 左向きなら左右を反転:x' = -(x + w) / facing left mirrors the box: x' = -(x + w)
  float x = facing > 0.0f ? local.x : -(local.x + local.w);
  return {feet.x + x, feet.y + local.y, local.w, local.h};
}

Mirroring a box isn't just negating x: the box's left edge becomes its right edge.
The punch's hit box from x = 37 to 51 becomes −51 to −37, so the new left edge is −(37 + 14) = −51.
The fighter turns the current frame's boxes into world boxes:

std::vector<Rect> Fighter::hurtboxes() const {
  std::vector<Rect> out;
  // ダウン中・起き上がり・KOは無敵(追い打ちなし) / invincible while down, getting up or KO'd (no hits on the ground)
  if (state == FighterState::Knockdown || state == FighterState::GetUp || state == FighterState::KO) return out;
  for (const Rect &r : data[frame].hurt) out.push_back(toWorld(r, position, facing));
  return out;
}

std::optional<Rect> Fighter::activeHitbox() const {
  if (phase() != MovePhase::Active || moveHit) return std::nullopt;
  const std::optional<Rect> &hit = data[frame].hit;
  if (!hit) return std::nullopt;
  return toWorld(*hit, position, facing);
}

A knocked-down, getting-up or KO'd fighter has no hurt boxes: no hits on the ground, so a knockdown can't be followed by endless hits on a body that can't defend.
activeHitbox is empty once the move has hit (moveHit), so a move hits at most once, even though its hit box overlaps the victim for several active frames.

Press F1 to see it all: here the kick is on frame 9 of 28, its first active frame, and Jin is in hit stun:

A 640 by 360 crop with the F1 overlay: Hayate&

The overlay draws the frame's hit box for the whole active window, faint after it has hit; during building, drawing activeHitbox() made the red box vanish the moment it connected, which looked like a bug in the collision rather than in the debug view.
The push boxes are wider than in chapter 30 (38 px standing instead of 28): at contact range the narrower ones let the bodies sink into each other.

31.6 One step of the fight

The order of things inside FightScene::update is where most of the fighting-game rules live:

The nine parts of one fight step in order: read both players&

void FightScene::update(float dt) {
  ++steps;
  Input &in = g.input;
  if (in.pressed(GLFW_KEY_ESCAPE)) {
    scenes().pop();
    return;
  }
  if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes;

  Controls controls[2] = {readControls(in, 0, pads[0]), readControls(in, 1, pads[1])};
  // バッファはヒットストップ中も記録する:止まっている間に押した技が、動き出した瞬間に出る
  // The buffers record during hit stop too: a move pressed while frozen comes out the moment things move again
  for (int i = 0; i < 2; ++i) {
    fighters[i].buffer.record(controls[i]);
    fighters[i].savePrevious(); // 止まっていても前の位置 = 今(補間で震えない) / even when frozen (no wobble)
  }
  effects.update(dt);
  for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1);
  shake = std::max(0, shake - 1);
  // ヒットストップ:当たった瞬間、数フレーム全部止める(重さが伝わる)。火花のアニメーションだけ進む
  // Hit stop: everything freezes for a few frames on contact (it sells the impact). Only the sparks keep animating
  if (hitstop > 0) {
    --hitstop;
    return;
  }
  victim = -1;

  float startX[2] = {fighters[0].position.x, fighters[1].position.x};
  bool threat[2];
  for (int i = 0; i < 2; ++i) {
    // 相手が近く(150ピクセル)で技の発生か持続にいる / the opponent is in a move's startup or active frames nearby
    const Fighter &o = fighters[1 - i];
    MovePhase p = o.phase();
    threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f;
  }
  for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]);
  separate();
  resolveHits();
  for (Fighter &f : fighters)
    if (f.landed) effects.dust(f.position, f.facing);

  // 体力の跡:0.5秒待ってから減る / the health trail: waits half a second, then drains
  for (int i = 0; i < 2; ++i) {
    if (trailDelay[i] > 0) --trailDelay[i];
    else trail[i] = std::max(static_cast<float>(fighters[i].health), trail[i] - 0.6f);
  }
  // 練習:KOから3秒で仕切り直し / training: restart 3 s after a KO
  if (koTime > 0 && ++koTime > 180) resetRound();
}

A few decisions in there:

  • Both fighters see the other's x from the start of the step (startX), as in chapter 30, so updating 1P first gives 1P no advantage.
  • savePrevious runs before the hit-stop return. During a freeze, previous = position every step, so the interpolation of chapter 26 draws the fighters still instead of wobbling between two old positions.
  • The threat check happens before the update, from the opponent's phase. It drives the proximity guard of 31.7.
  • Hits are resolved after separate, at the step's final positions.

31.7 Resolving hits

Contacts first, then apply: trades

A contact is the attacker's hit box overlapping any of the victim's hurt boxes.
Both directions are checked before either is applied:

void FightScene::resolveHits() {
  // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう
  // The move is remembered here: in a trade the first takeHit clears the second attacker's move
  struct Contact {
    int attacker;
    const MoveData *move;
    Rect where;
    bool blocked;
  };
  Contact contacts[2];
  int count = 0;
  for (int i = 0; i < 2; ++i) {
    Fighter &a = fighters[i], &v = fighters[1 - i];
    std::optional<Rect> hit = a.activeHitbox();
    if (!hit) continue;
    for (const Rect &hurt : v.hurtboxes()) {
      if (!overlaps(*hit, hurt)) continue;
      contacts[count++] = {i, a.move, intersection(*hit, hurt), v.canBlock(a.move->height, a.position.x)};
      break;
    }
  }

If both fighters hit each other on the same step, both hits happen: a trade.
Checking 1P's hit and applying it before checking 2P's would let 1P always win ties, the same fairness problem as the update order.
There's a trap here, though, and it crashed the game when two CPU fighters (chapter 32) traded hits: takeHit clears the victim's move pointer, and in a trade the victim of the first contact is the attacker of the second.
The second contact then read a.move, which was nullptr by then.
That's why Contact stores the MoveData pointer at the moment the contact is found.
The guard decision is also made in the first loop, from both fighters' input of this step, before anyone's state changes.

Then the contacts are applied:

  float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end)
  for (int c = 0; c < count; ++c) {
    int i = contacts[c].attacker;
    Fighter &a = fighters[i], &v = fighters[1 - i];
    const MoveData &m = *contacts[c].move;
    a.confirmHit();
    bool wasHit = v.state == FighterState::Hitstun;
    HitResult r = v.takeHit(m, a.facing, contacts[c].blocked);
    // 壁際:相手が下がれないので自分が下がる(壁で永久に固めさせない) / at the wall the opponent cannot move back,
    // so the attacker is pushed back instead (no endless corner pressure)
    if (atWall(v)) push[i] = m.knockback * 0.7f;
    bool blocked = r == HitResult::Blocked;
    int stop = blocked ? m.hitstop - 3 : m.hitstop;
    if (r == HitResult::KO) {
      stop = 40;
      koTime = 1;
    }
    hitstop = std::max(hitstop, stop);
    victim = 1 - i;
    top = i;
    bool heavy = m.damage >= 10 || r == HitResult::KO;
    if (heavy && !blocked) shake = stop;
    Rect w = contacts[c].where;
    effects.spark(w.centre(), blocked, heavy);
    // 記録(台本で動かしたときの確認に) / a log line (to check scripted runs)
    static const char *const kResult[] = {"hit", "blocked", "KO"};
    printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name,
           v.name.c_str(), kResult[static_cast<int>(r)], v.health, blocked ? 0 : v.combo, stop);
    if (!blocked) {
      trailDelay[1 - i] = 30;
      if (wasHit && v.combo >= 2) {
        comboHits[i] = v.combo;
        comboTime[i] = 90;
      }
    }
  }
  // 押し返しは全部のノックバックの後:相打ちで受けたノックバックを消さず、どちらの接触が先でも結果は同じ
  // Push-backs come after every knockback: in a trade they never cancel the knockback the attacker just took, and
  // the result is the same whichever contact was applied first
  for (int i = 0; i < 2; ++i)
    if (push[i] > 0.0f) fighters[i].pushBack(push[i]);
}

The printf line is the hit log you saw in 31.3; it's what I used to check scripted fights like the clip.
The push array and the loop at the end are the corner push-back, explained with knockback below.

Guarding

Guarding in this game, as in most 2D fighters, is "hold away from the opponent":

bool Fighter::canBlock(AttackHeight height, float attackerX) const {
  bool canGuard = actionable() || state == FighterState::Blockstun;
  if (!canGuard || !onGround) return false;
  bool away = attackerX > position.x ? controls.left : controls.right; // 相手と反対を押す / holding away
  if (!away) return false;
  if (height == AttackHeight::Low && !controls.down) return false; // 下段はしゃがんで / lows: crouch
  if (height == AttackHeight::High && controls.down) return false; // 飛び込みは立って / jump-ins: stand
  return true;
}

"Away" is computed from the two positions, not from the fighter's facing: after a jump over the opponent the facing is stale for a moment (it only updates in free ground states), but the guard still has to be the side the attack comes from.
The attack's height adds the classic rule of thumb that keeps guarding from being a single button:

Height Moves Stand guard Crouch guard
mid punch, kick, crouching punch blocks blocks
low sweep gets hit blocks
high jump kick blocks gets hit

A crouching guard beats lows, a standing guard beats jump-ins, and the attacker can mix the two.
In the clip, Jin's jump kick hits Hayate in a crouching guard for exactly this reason.

Proximity guard

The first version of this code had a funny bug: nothing was ever blocked.
The defender pressed back as the punch started, and back means walking away at 100 px/s; by the time the punch became active, the defender had walked out of its range, and never actually blocked anything.
Real fighting games solve this with a proximity guard: while an attack is coming, holding back holds the guard pose in place instead of walking.
threat from 31.6 (the opponent in startup or active frames within 150 px) does that in the free-ground-state branch of Fighter::update:

    bool fwd = forward(c, facing), bwd = back(c, facing);
    if (c.up) {
      jumpDirection = fwd ? 1.0f : bwd ? -1.0f : 0.0f;
      velocity = {0.0f, 0.0f};
      setState(FighterState::JumpSquat);
    } else if (c.down) {
      velocity.x = 0.0f;
      guarding = bwd && threat;
      setState(FighterState::Crouch);
    } else if (bwd && threat) {
      // 近接ガード:攻撃が来るときに後ろを押すと、下がらずにその場で構える / proximity guard: holding back while an
      // attack is coming guards in place instead of walking away
      velocity.x = 0.0f;
      guarding = true;
      setState(FighterState::Idle);

guarding only chooses the block / cblock sprite; whether a hit is blocked is still canBlock's decision at the moment of contact.

Taking a hit

HitResult Fighter::takeHit(const MoveData &m, float attackerFacing, bool blocked) {
  move = nullptr;
  if (blocked) {
    stun = m.blockstun;
    state = FighterState::Blockstun;
    stateTime = 0;
    velocity.x = attackerFacing * m.knockback * 0.8f;
    return HitResult::Blocked;
  }
  // のけぞり中・ダウンで飛ばされている間に当たればコンボ / hits during hit stun (or while thrown) add to the combo
  combo = state == FighterState::Hitstun || state == FighterState::Knockdown ? combo + 1 : 1;
  health = std::max(0, health - m.damage);
  if (health == 0) {
    state = FighterState::KO;
    stateTime = 0;
    onGround = false;
    velocity = {attackerFacing * 190.0f, -430.0f};
    return HitResult::KO;
  }
  if (m.knockdown || !onGround) {
    // 足払い、または空中で当たった:ダウン / a sweep, or hit in the air: knocked down
    state = FighterState::Knockdown;
    stateTime = 0;
    onGround = false;
    velocity = {attackerFacing * 140.0f, m.knockdown ? -260.0f : -200.0f};
    return HitResult::Hit;
  }
  stun = m.hitstun;
  state = FighterState::Hitstun;
  stateTime = 0;
  velocity.x = attackerFacing * m.knockback;
  return HitResult::Hit;
}

  • Blocked: block stun, 0.8 × the knockback, no damage, no combo.
  • The combo grows only if the victim was still in hit stun (or flying from a knockdown) when hit; otherwise it starts again at 1. That one line is the whole combo system, and it's why the link of 31.3 depends on one frame.
  • A knockdown (the sweep, or any hit in the air) throws the victim up and back; landing starts 40 frames of lying (kLieFrames) and then 14 frames of GetUp, both invincible.
  • Health 0 is a KO: a bigger throw, and the fighter stays down.

Knockback and the corner

Knockback is just a velocity: takeHit sets velocity.x, and from then on ground friction of 1400 px/s² slows it down in update.
With friction applied every 1/60 s step, a punch's 140 px/s slides the victim about 6 px and a kick's 230 px/s about 17 px.
That's what pushes the fighters apart after every hit; a punch moves the victim so little that the second punch of the link still reaches.
But a victim with its back to the stage edge can't slide.
Without a rule, the attacker could stay in range forever and keep the victim locked in the corner.
So when the victim is at the wall, the attacker is pushed back instead, at 0.7 × the knockback (push in resolveHits above):

Two side views. Mid-stage, the attacker hits the victim and the victim slides away from the attacker with the knockback. In the corner, the victim&

  void confirmHit() { moveHit = true; } // この技はもう当たった(一回の技で一度だけ) / this move has hit (once per move)
  // 壁際で当てたら自分が下がる。同じ向きのもっと速い動き(相打ちで受けたノックバック)は其のまま / pushed back at
  // the wall; a faster motion the same way (the knockback just taken in a trade) is kept
  void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); }

pushBack moves the fighter against its facing, which is away from the opponent, since a fighter who just hit faces its victim.

resolveHits doesn't call pushBack inside the contact loop.
It only notes the speed in push[i] and applies the push-backs after the loop, once every knockback has been set.
In a trade at the wall, the attacker is also the victim of the other contact, and with pushBack inside the loop the contact applied second won.
With Jin cornered, Hayate's push-back was overwritten by the knockback from Jin's hit; with Hayate cornered, Jin's knockback was overwritten by his weaker push-back.
So the same trade played out differently on the two sides of the screen: in a test with two punches trading at the wall, the fighter in front slid 5.8 px away when Jin was the cornered one, but only 2.6 px when Hayate was.
That's the fairness problem of trades again, this time in what gets applied rather than in what gets checked.
The std::max in pushBack keeps the faster of the two motions away from the opponent, and now it's 5.8 px in both corners.

31.8 Hit stop and screen shake

On contact, both fighters freeze for a few frames: 7 for the punches, 10 for the sweep and the jump kick, 11 for the kick, 3 fewer on block, and 40 for the K.O.
It's called hit stop (or hit lag), and it's one of the strongest tricks in game feel: the freeze tells your eyes that something solid happened, a bit like the pause at the top of a hammer swing.
In the code it's the early return in update you saw in 31.6.
Everything that should still move during the freeze is above that line: the effects (the spark animates while the fighters stand still) and the input buffers.

Two things shake.
The victim's body jitters ±2 px every step during the freeze (the shake argument of Fighter::draw), and for heavy hits (10 damage or more, or a KO) the camera jumps by 2 px sideways and 1 px up and down:

void FightScene::draw(float alpha) {
  SpriteBatch &b = g.batch;
  Camera2D view = camera;
  // 画面の揺れ:重い一撃のヒットストップ中、カメラを2ピクセルずつ揺らす / screen shake: during a heavy hit's
  // hit stop the camera jumps by 2 pixels
  if (shake > 0) view.centre += Vec2{shake % 2 ? 2.0f : -2.0f, shake % 4 < 2 ? 1.0f : -1.0f};
  b.begin(view.matrix(), SpriteSort::Layer);
  drawBackground();
  for (int i = 0; i < 2; ++i)
    fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0);
  effects.draw(b);
  if (g.showBoxes) drawDebug(alpha);
  b.end();
  // HUDは揺らさない / the HUD does not shake
  b.begin(camera.matrix(), SpriteSort::Layer);
  drawHud();
  b.end();
}

The HUD goes into a second batch with the unshaken camera, so the health bars stay put.
The first version of the shake showed the clear color at the edges of the screen; the background is now drawn 8 px larger than the view on every side.
The fighter who attacked last is drawn on top (layer 3 instead of 2), so a punch is never hidden behind the body it hits.

31.9 Knockdowns, the KO, health bars and the combo counter

The K.O. screen: a big red K.O. with a dark outline and drop shadow over the dojo, Jin lying flat on the right with three small stars circling his head, Hayate standing, and Jin&

The health bars sit in the canvas, anchored at the center side and draining from the outer end, as fighting games always draw them.
Each one is layered rectangles: an outline, the dark background, a white trail, and the gold health in front with a light and a dark edge:

  auto part = [&](float amount) {
    float w = std::round(r.w * std::clamp(amount / static_cast<float>(kMaxHealth), 0.0f, 1.0f));
    return rightSide ? Rect{r.x, r.y, w, r.h} : Rect{r.right() - w, r.y, w, r.h};
  };
  b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f);
  bool low = health <= kMaxHealth * 0.25f;
  Rect h = part(health);
  b.drawRect(h, low ? hexColor(0xe8483cff) : kGold, 10.3f);

The trail is what makes damage readable: after a hit it waits 30 frames (trailDelay, half a second), then drains 0.6 health per frame, so the 12 of a kick shrink away in 20 frames and you can see how much the last combo took.
At 25 health or less the bar turns red.
The bars are 272 px wide, so one point of health is 2.72 px, which is why part rounds the width to whole pixels.

"2 HITS" appears on the attacker's side for 90 frames when a hit landed on a victim already in hit stun (wasHit && v.combo >= 2 in resolveHits).
The K.O. banner is pixel12 at scale 5 with an outline drawn in 8 directions and a drop shadow, and three seconds (180 steps) after a K.O. resetRound puts both fighters back: this is a training mode, and chapter 32 adds rounds and a win screen.

31.10 A 2D scene graph

Our fighters are single sprites, one frame at a time, generated with everything in them.
A few things don't fit that:

  • The headband tails should flutter with the fighter's motion, not with the frame: two segments, each swinging relative to the previous one.
  • The dizzy stars circle the head of a knocked-out fighter, passing in front of and behind it.
  • The shadow stays on the floor while the body jumps, and shrinks with height.
  • The sparks and dust live for a few frames at some point in the world.

All of them hang off something that moves: a tail off the headband knot, which is a different pixel in every frame; the stars off the head; everything off the fighter, who may face left or right.
That's a transform hierarchy: every node has a transform relative to its parent, and its world transform is the parent's world transform times its own.
We built the same thing in 3D in chapter 14 for glTF nodes, using the matrix product of linear algebra chapter 7; here it's the 2D version, which needs a 2 × 3 matrix.

Affine2: a 2 × 3 matrix

In 2D, a rotation and scale are a 2 × 2 matrix and a translation is a vector.
Together they're the top two rows of a 3 × 3 homogeneous matrix (linear algebra chapter 9); the bottom row is always (0, 0, 1), so we don't store it:

𝐀=[xxyxtxxyyyty],𝐩′=𝐀[pxpy1]=px𝐱+py𝐲+𝐭

The columns have a meaning: x and y are where the node's own x and y axes end up, t is where its origin ends up.

// 2Dのアフィン変換(2×3):p' = x·p.x + y·p.y + t。xとyは変換後の軸(列)、tは移動
// A 2D affine transform (2 × 3): p' = x·p.x + y·p.y + t. x and y are the transformed axes (columns), t the translation
struct Affine2 {
  Vec2 x = {1.0f, 0.0f};
  Vec2 y = {0.0f, 1.0f};
  Vec2 t = {0.0f, 0.0f};

  // 拡大 → 回転 → 移動(T·R·S)。回転は画面上で時計回り(y下向き、SpriteBatchと同じ)
  // scale → rotate → translate (T·R·S). Rotation is clockwise on screen (y down, as in SpriteBatch)
  static Affine2 trs(Vec2 position, float rotation, Vec2 scale);
  Vec2 apply(Vec2 p) const { return x * p.x + y * p.y + t; }
  float determinant() const { return x.x * y.y - x.y * y.x; } // 負 = 鏡に映した / negative = mirrored
};
// a × b:先にb、次にa(親 × 子) / a × b: b first, then a (parent × child)
Affine2 operator*(const Affine2 &a, const Affine2 &b);

trs builds scale, then rotation, then translation, exactly the 𝐓𝐑𝐒 order of the linear algebra series:

𝐑𝐒=[cosθ−sinθsinθcosθ][sx00sy]=[sxcosθ−sysinθsxsinθsycosθ]

Affine2 Affine2::trs(Vec2 position, float rotation, Vec2 scale) {
  float c = std::cos(rotation), s = std::sin(rotation);
  // 回転行列の列 (c, s) と (-s, c) に、それぞれの拡大を掛ける / the rotation's columns (c, s) and (-s, c), each times
  // its scale
  return {.x = Vec2{c, s} * scale.x, .y = Vec2{-s, c} * scale.y, .t = position};
}

It's the usual rotation matrix, but since our y axis points down, a positive angle turns clockwise on screen, which is also what SpriteBatch does with Sprite::rotation, so the two agree.
The product of two Affine2 is the 3 × 3 product with the bottom rows left out: b's axes go through a's 2 × 2 part, and b's origin goes through all of a:

  return {.x = a.x * b.x.x + a.y * b.x.y, .y = a.x * b.y.x + a.y * b.y.y, .t = a.apply(b.t)};

The determinant of the 2 × 2 part (linear algebra chapter 10) is the area scale, and its sign says whether the transform mirrors.
For a trs, it's sxsy: a fighter facing left has scale (−1, 1) and a determinant of −1.

Node

// ノード:ローカルの変換、描くスプライト(なくてもよい)、子供たち。子はunique_ptrなので、ノードへのポインタは
// 親が動いても(vectorが伸びても)変わらない
// A node: a local transform, an optional sprite, children. Children are unique_ptrs, so pointers to nodes stay valid
// when the parent moves (or its vector grows)
class Node {
public:
  explicit Node(std::string nodeName = {}) : name(std::move(nodeName)) {}

  // 子を足して、その参照を返す / adds a child and returns a reference to it
  Node &add(std::string childName);
  Node &add(std::unique_ptr<Node> child);
  // 子を外す(なければ何もしない) / removes a child (nothing if it is not one)
  void remove(const Node *child);
  // 名前で子孫を探す(深さ優先、なければnullptr) / finds a descendant by name (depth first, nullptr if missing)
  Node *find(std::string_view childName);

  Affine2 local() const { return Affine2::trs(position, rotation, scale); }
  // 木をたどって描く:自分のスプライト、次に子供たち。layerOffsetは全部のスプライトのlayerに足す
  // Draws the tree: own sprite first, then the children. layerOffset is added to every sprite's layer
  void draw(SpriteBatch &batch, const Affine2 &parentWorld = {}, float layerOffset = 0.0f) const;

  std::string name;
  Vec2 position = {0.0f, 0.0f}; // 親の座標系で / in the parent's space
  float rotation = 0.0f;        // ラジアン、時計回り / radians, clockwise
  Vec2 scale = {1.0f, 1.0f};    // (-1, 1) = 左右反転。回転した子の親に縦横違う拡大は不可(せん断になる)
                                // (-1, 1) = mirrored. No non-uniform scale above a rotated child (that would shear)
  bool visible = true;          // falseなら子供ごと描かない / false hides the whole subtree
  // 描くスプライト:positionは無視(ノードの原点に描く)、originが回転と位置の基準、sizeは拡大前
  // The sprite to draw: its position is ignored (drawn at the node's origin), origin is the pivot, size is unscaled
  std::optional<Sprite> sprite;
  std::vector<std::unique_ptr<Node>> children;
};

Children are std::unique_ptr<Node>, so a Node * into the tree stays valid when a parent's vector of children grows, which is what lets Fighter keep plain pointers to its parts and Effects keep pointers to its live effects.
Drawing walks the tree, multiplying as it goes down:

void Node::draw(SpriteBatch &batch, const Affine2 &parentWorld, float layerOffset) const {
  if (!visible) return;
  Affine2 world = parentWorld * local();
  if (sprite) {
    Sprite s = toSprite(*sprite, world);
    s.layer += layerOffset;
    batch.draw(s);
  }
  for (const auto &c : children) c->draw(batch, world, layerOffset);
}

There are no parent pointers and no cached world matrices: the world transform exists only on the way down, which is all drawing needs.
(Challenge 6 is about what you need when you want a node's world position at another time.)
layerOffset lets the scene put a whole fighter on layer 2 or 3, while each part keeps a small relative layer like −0.2 for "just behind the body".
Nothing in scene_graph.hh is specific to this game; it could move into the engine later.

toSprite and mirroring

SpriteBatch doesn't take matrices.
A Sprite has a position, a size, a rotation, an origin (the pivot, as a fraction of the size) and flipX.
So toSprite has to turn a world transform back into those:

Sprite toSprite(const Sprite &sprite, const Affine2 &world) {
  Sprite s = sprite;
  float sx = std::hypot(world.x.x, world.x.y), sy = std::hypot(world.y.x, world.y.y);
  s.position = world.t;
  s.size = {sprite.size.x * sx, sprite.size.y * sy};
  if (world.determinant() >= 0.0f) {
    s.rotation = std::atan2(world.x.y, world.x.x);
  } else {
    // 鏡像:world = R(θ)·diag(-sx, sy)。x軸は -(cos θ, sin θ) を向くので θ = atan2(-x.y, -x.x)。
    // 絵を左右反転し、基準点も反対側へ(origin.x → 1 - origin.x)
    // Mirrored: world = R(θ)·diag(-sx, sy). The x axis points along -(cos θ, sin θ), so θ = atan2(-x.y, -x.x).
    // Mirror the picture and move the pivot to the other side (origin.x → 1 - origin.x)
    s.rotation = std::atan2(-world.x.y, -world.x.x);
    s.flipX = !s.flipX;
    s.origin.x = 1.0f - s.origin.x;
  }
  return s;
}

The size comes from the lengths of the two columns, the rotation from the direction of the x column.
That works as long as the transform is a rotation times a scale with positive factors.
A fighter facing left has scale (−1, 1) at the top of its tree, so every part below it has a determinant below zero, and no rotation can produce that.
But any 2 × 2 matrix with perpendicular columns and a negative determinant can be written as a rotation times a mirror:

𝐌=𝐑(θ)[−sx00sy]

Its x column is −sx(cosθ,sinθ), so θ=atan2(−xy,−xx), and the mirror itself becomes flipX.
The pivot has to move too: the tail's root is at 1/12 of the sprite's width from its left edge, and in the flipped picture the root is at 11/12.

Two panels with the same headband tail sprite. Facing right, the determinant is plus 1, the sprite&

This is what lets the whole fighter be mirrored by one scale at the root: tails, stars and shadow follow without any part knowing which way the fighter faces.

The fighter's tree

The fighter&

// 体の部品の木を作る。コマ(body)は一枚の絵、そこに鉢巻の尾(回る部品の鎖)と星(ダウン中)と影を付ける
// Builds the parts tree. The frame (body) is one picture; the headband tails (a chain of rotating parts), the stars
// (while down) and the shadow are attached to it
void Fighter::buildParts(const SpriteSheet &fx, const char *tail) {
  root = std::make_unique<Node>("fighter");
  shadow = &root->add("shadow");
  shadow->sprite = fx.sprite(fx.find("shadow"), {}, {0.5f, 0.5f});
  shadow->sprite->color = {1.0f, 1.0f, 1.0f, 0.35f};
  shadow->sprite->layer = -1.5f; // どのファイターよりも奥 / behind both fighters
  body = &root->add("body");
  body->sprite = sheet.sprite(frame, {}, kPivot);
  // 頭のソケット → 星の輪(縦につぶす)→ 星(つぶれを打ち消す) / the head socket → the star ring (squashed
  // vertically) → stars (canceling the squash)
  head = &body->add("head");
  stars = &head->add("stars");
  stars->position = {0.0f, -13.0f};
  stars->scale = {1.0f, 0.35f};
  stars->visible = false;
  for (Node *&n : starNodes) {
    n = &stars->add("star");
    n->scale = {1.0f, 1.0f / 0.35f};
    n->sprite = fx.sprite(fx.find("star"), {}, {0.5f, 0.5f});
  }
  // 結び目 → 尾1 → 尾2:子は親の回転を受け継ぐので、尾2のrotationは尾1に対する曲がりだけ
  // knot → tail 1 → tail 2: a child inherits its parent's rotation, so tail 2's rotation is only its bend relative
  // to tail 1
  knot = &body->add("knot");
  int t = fx.find(tail);
  Vec2 tailOrigin = {1.0f / 12.0f, 0.5f}; // 左の真ん中が付け根 / the root is at the left middle
  tail1 = &knot->add("tail1");
  tail1->sprite = fx.sprite(t, {}, tailOrigin);
  tail1->sprite->layer = -0.2f; // 体の後ろ / behind the body
  tail2 = &tail1->add("tail2");
  tail2->position = {9.0f, 0.0f};
  tail2->scale = {0.85f, 0.85f};
  tail2->sprite = tail1->sprite;
}

Every frame, draw sets the nodes that depend on the frame and the position, then draws the tree:

void Fighter::draw(SpriteBatch &batch, float alpha, float layer, int shake) {
  Vec2 p = lerp(previous, position, alpha);
  root->position = {std::round(p.x), kGroundY};
  root->scale = {facing, 1.0f};
  float shakeX = shake ? static_cast<float>((shake % 2) * 4 - 2) : 0.0f; // ヒットストップ中の震え / hit-stop shake
  body->position = {shakeX, std::round(p.y - kGroundY)};
  body->sprite->uv = sheet.uv(frame);
  const FrameBoxes &fb = data[frame];
  head->position = fb.head;
  knot->position = fb.knot;
  float height = std::clamp((kGroundY - p.y) / 100.0f, 0.0f, 1.0f);
  float s = 1.0f - 0.4f * height;
  shadow->scale = {s, s};
  shadow->position = {0.0f, -1.0f};
  root->draw(batch, {}, layer);
}

head and knot take their positions from the frame's sockets, so the stars follow the head into the lying KO frame and the tails stay on the knot in every pose, with no per-frame work by anyone.
The shadow is a child of the root, not of the body, so it stays on the floor during a jump, shrinking to 0.6 of its size 100 px up.
Its layer of −1.5 puts it below both fighters, whichever is on top.

Headband tails: a chain of rotations

Each tail segment's angle chases a target with a damped spring, in facing-right space (the root's mirror takes care of facing left):

// 部品の動き(ステップごと):鉢巻の尾はばねで角度を追いかけ、星は頭の周りを回る
// Part motion (per step): the headband tails chase their angles with springs, the stars circle the head
void Fighter::updateParts(float dt) {
  // 右向きの空間で考える(左向きはrootの拡大(-1, 1)が鏡に映す)。角度π = 後ろ向き、π − a = 後ろで少し下がる
  // Think in facing-right space (root's scale (-1, 1) mirrors it when facing left). Angle π = pointing back,
  // π − a = back and drooping a little
  float vx = velocity.x * facing, vy = velocity.y;
  float droop = 0.5f - std::clamp(vx / 260.0f, -0.3f, 0.4f) + std::clamp(-vy / 700.0f, -0.7f, 0.7f);
  float target[2] = {kPi - droop + 0.12f * std::sin(time * 8.0f), 0.0f};
  for (int i = 0; i < 2; ++i) {
    if (i == 1) target[1] = tailAngle[0] - 0.25f + 0.25f * std::sin(time * 8.0f - 1.3f); // 尾2は尾1を少し遅れて
                                                                                          // tail 2 lags tail 1
    tailSpeed[i] += ((target[i] - tailAngle[i]) * 160.0f - tailSpeed[i] * 16.0f) * dt;
    tailAngle[i] += tailSpeed[i] * dt;
  }
  tail1->rotation = tailAngle[0];
  tail2->rotation = tailAngle[1] - tailAngle[0]; // 親(尾1)に対する角度 / relative to the parent (tail 1)

  // 星:つぶした輪の上を回る。手前の半分は顔の前、奥の半分は後ろに描く / stars: around the squashed ring; the near
  // half in front of the face, the far half behind
  bool down = (state == FighterState::Knockdown || state == FighterState::KO) && onGround;
  stars->visible = down;
  for (int i = 0; i < 3; ++i) {
    float a = time * 5.0f + static_cast<float>(i) * 2.0944f;
    starNodes[i]->position = {std::cos(a) * 13.0f, std::sin(a) * 13.0f};
    starNodes[i]->sprite->layer = std::sin(a) > 0.0f ? 0.3f : -0.3f;
  }
}

The target comes from the velocity in facing space: angle π points straight back, and droop lowers it.
Standing, the tail hangs 0.5 rad down; walking forward it streams back almost level; flying upward it hangs, and falling it flies up, plus a sine flutter.
The spring is the same semi-implicit Euler as the fighter's physics in chapter 30, with a stiffness of 160 and damping of 16: ω=160≈12.6 rad/s and a damping ratio of 16/(2⋅12.6)≈0.63, so it overshoots by about 8 % and settles, like cloth with some weight.

The hierarchy lesson is the line tail2->rotation = tailAngle[1] - tailAngle[0].
tailAngle[1] is tail 2's angle in the world (in facing space), but tail 2 is a child of tail 1 and inherits tail 1's rotation.
Its local rotation must be only the bend relative to its parent, a2−a1; setting it to a2 would turn it by a1+a2.

The headband tail chain. Tail1 is attached at the knot socket and rotated by a1, measured clockwise from the zero direction. Tail2 is attached 9 pixels along tail1, its local rotation is the angle a2 minus a1 between tail1&

The angles are chased in the world and converted to local at the end, because the physics (droop, lag) is easier to think about in the world.
A skeletal animation system does the opposite conversion all the time.

Dizzy stars: canceling a squash

The stars should circle the head on a flat ellipse, as if seen from slightly above.
The easy way to get an ellipse is to move the stars on a circle of radius 13 inside a parent that's squashed to (1, 0.35).
But then the stars themselves are squashed too.
So each star has the opposite scale, (1, 1 / 0.35), and the product is the identity:

[1000.35][10010.35]=[1001]

The positions are squashed (the parent scales the child's translation), the stars aren't:

Three panels. In the stars node&

A star on the near half of the ellipse (positive sin, lower on screen) gets layer +0.3 and is drawn in front of the face, the far half −0.3 behind it, so they really seem to go around.
They turn at 5 rad/s, a lap every 1.26 s.

Three crops of the game at twice their size: Jin&

Shadow and effects

Sparks and dust are nodes under an effects root that the scene draws on its own.
Each live effect is a node plus an Animator and a velocity:

void Effects::spawn(const AnimationClip *clip, Vec2 at, float rotation, Vec2 scale, Vec2 velocity, float layer) {
  if (!clip) return;
  Node &n = root.add("effect");
  n.position = at;
  n.rotation = rotation;
  n.scale = scale;
  n.sprite = sheet.sprite(clip->frames[0], {0.0f, 0.0f}, {0.5f, 0.5f});
  n.sprite->layer = layer;
  Live l{&n, {}, velocity};
  l.animator.play(clip, true);
  live.push_back(l);
}

void Effects::dust(Vec2 at, float facing) {
  spawn(dustClip, at + Vec2{-facing * 10.0f, -5.0f}, 0.0f, {-facing, 1.0f}, {-facing * 40.0f, -8.0f}, 1.8f);
  spawn(dustClip, at + Vec2{facing * 10.0f, -5.0f}, 0.0f, {facing, 1.0f}, {facing * 25.0f, -6.0f}, 1.8f);
}

void Effects::update(float dt) {
  for (Live &l : live) {
    l.animator.update(dt);
    l.node->position += l.velocity * dt;
    if (!l.animator.finished()) l.node->sprite->uv = sheet.uv(l.animator.frame());
  }
  // 終わったものを外す(ノードもlistも) / remove finished ones (the node and the list entry)
  for (Live &l : live)
    if (l.animator.finished()) root.remove(l.node);
  std::erase_if(live, [](const Live &l) { return l.animator.finished(); });
}

A spark appears at the center of the overlap of the hit box and the hurt box it touched (intersection in resolveHits), rotated randomly by an Rng with the fixed seed 31 so every run looks the same, twice as large for heavy hits, blue for guards.
Two dust puffs appear at every landing, one of them mirrored with scale (−facing, 1): the same mirroring trick as the fighter, used on a single node.
A finished effect removes its node, which is safe because update collects the finished ones after animating all of them.

The limitation: no shear

There's one thing our scene graph can't draw.
A non-uniform scale above a rotated child produces a transform whose columns aren't perpendicular any more, a shear (linear algebra chapter 8).
Take a parent with scale (1, 0.5) and a child rotated by 45°:

𝐒𝐑=[1000.5][0.71−0.710.710.71]=[0.71−0.710.350.35]

The columns (0.71, 0.35) and (−0.71, 0.35) have the dot product −0.5 + 0.125 = −0.375, not 0: they're about 127° apart, and the child's square becomes a parallelogram.
A Sprite is always a rectangle (a position, a size, one rotation), so toSprite can't express it and draws the wrong shape: a rectangle with the right side lengths, turned to the x column.
The other order is fine: a rotated parent above a non-uniformly scaled child gives 𝐑𝐒, whose columns stay perpendicular.

Two panels. Left: a rotated parent with a non-uniformly scaled child gives R times S, a rotated rectangle, which a sprite can draw. Right: a parent with scale 1, 0.5 above a child rotated 45 degrees gives S times R with columns 0.71, 0.35 and minus 0.71, 0.35, 127 degrees apart: the true shape is an orange parallelogram, while toSprite draws a dashed red rectangle

That's why the stars' squashing parent has no rotated child (the stars only move, they never turn), and why mirroring is fine: a scale of ±1 never shears anything, because diag(−1,1)𝐑(θ)=𝐑(−θ)diag(−1,1).
The rule is in the comment on Node::scale.
Engines that allow it draw each node as a general quad of four transformed corners, which is challenge 7.

31.11 Running it, and platform notes

From the project root:

cmake --build build
./build/games/fighter/fighter

In Visual Studio, pick fighter as the startup item; the executable is build\games\fighter\Debug\fighter.exe, and it runs with the project root as its working directory, like every game since chapter 25.

  • All: two players on one keyboard need the keyboard to report many keys at once. Cheap keyboards often can't (key rollover, "ghosting"): with W, D and F held, a fourth key may simply not arrive. If one player's presses go missing while the other holds several keys, try other keys or a gamepad. That's also why 2P has keypad alternatives.
  • All: laptops without a numeric keypad use K and L for 2P.
  • Gamepads use GLFW 3.3's gamepad API (glfwGetGamepadState, SDL-style mappings). I couldn't test them in the headless harness this series is checked with, which has no joysticks, so treat that path as untested on real hardware.
  • Windows: the help bar contains Japanese, which needs MSVC's /utf-8 option (chapter 26's platform notes); the project's CMake already sets it for MSVC, so the text should never show up as ?.
  • Linux, FreeBSD: run from the project root, or the game can't find games/fighter/assets/.

31.12 How real fighting games do it

  • Frame data is how the genre talks. Street Fighter 6 shows startup, active and recovery frames and the advantage on a frame meter in its training mode, and players learn the numbers by heart. Our moves follow the usual shapes: fast weak punches with good advantage, slow strong kicks that are unsafe on block, sweeps that knock down and leave a big opening.
  • Boxes are authored per frame in internal tools, often on top of 3D models posed like 2D frames. Arc System Works' Guilty Gear Xrd drew its 3D characters with hand-picked key poses at a lower frame rate to look like 2D animation, a cousin of our skeleton-to-pixels pipeline.
  • Hit stop, proximity guard, block stun pushback and corner pushback are all standard; so are rules we don't have yet: counter hits (extra stun when you hit a move in its startup, challenge 5), throws (which beat guarding, so guarding can't be the answer to everything) and cancels (interrupting a move's recovery with a special move, a combo that doesn't need a link).
  • Input buffers are everywhere, and the window is a tuning decision: longer is friendlier, shorter is stricter. Special-move inputs like quarter circles have their own, longer buffers.
  • Determinism: our fixed step, seeded Rng and "everything is data" design is exactly what rollback netcode (GGPO and its descendants) needs: both machines run the same steps from the same inputs, and when a remote input arrives late, the game rolls back a few frames and re-simulates them.
  • 2D scene graphs: Godot's Node2D uses Transform2D, a 2 × 3 matrix stored as three vectors x, y and origin, like Affine2; Unity's Transform hierarchy is the 3D version. 2D skeletal animation tools such as Spine attach images to bone hierarchies like our tails, and they draw meshes instead of quads, so shear isn't a problem for them.

31.13 Summary

  • Moves are frame data: startup, active and recovery frames, damage, hit stun, block stun, hit stop, knockback and height in one table (moves.cc). The move's frame counter picks the sprite (frames[phase]), so the art can't drift from the rules; the press step is frame 1.
  • Frame advantage = stun − (remaining active frames + recovery): punch +7 on hit and 0 on block, kick 0 and −6, crouching punch +5 and −1, sweep −10 on block. In this code a move links when the advantage is at least its startup + 3, because the step a move ends only returns the fighter to Idle, the hit lands on the frame after startup, and the victim is free on the step the stun reaches 0. Punch hit stun 17 is the smallest that links punch → punch; 16 is one frame short (checked in the game).
  • Input buffer: the age of each button's last press; a move fires if the press is at most 8 frames old when the fighter is free, and consumes it. It records during hit stop too.
  • Boxes: hurt boxes, a hit box and sockets per animation frame in fighter.boxes, generated from the same poses as the art; facing left mirrors a box with x' = −(x + w). No hurt boxes on the ground; a move hits once.
  • Hits: collect contacts in both directions first, then apply them, so trades work; store the move pointer in the contact, because takeHit clears the victim's move. Guard = hold away (from positions); lows need a crouch, jump kicks a standing guard; proximity guard holds the pose while an attack is coming.
  • Hit stop freezes the fighters for 7 to 11 frames (3 fewer on block, 40 for a KO) while sparks animate and inputs are still buffered; the victim and, for heavy hits, the camera shake; the HUD doesn't.
  • Knockback is a velocity eaten by friction; at the stage edge the attacker is pushed back instead, after every knockback has been set and never slower than a knockback it already has, so a trade at the wall comes out the same in both corners. Health bars drain from the outside with a trail; the combo counter shows hits on a victim still in hit stun.
  • Scene graph: Affine2 (2 × 3, trs, parent × child), Node with unique-pointer children and draw multiplying on the way down, toSprite turning a world transform into a sprite; a negative determinant becomes flipX with origin.x → 1 − origin.x. Tails are a chain where the child's rotation is only the bend relative to its parent; stars cancel their parent's squash. No non-uniform scale above a rotated child: that's a shear, and a sprite is always a rectangle.

31.14 Challenges

  1. ★ Change PUNCH's hit stun from 17 to 16 and run the clip's script (or press F twice quickly next to Jin). The log line of the second punch should still say step 109 but combo 1, and "2 HITS" should never appear, because the second punch becomes active on the very step Jin's stun ends.
  2. ★ With pen and paper and this chapter's rule (a link needs an advantage of at least startup + 3), decide which of these link on hit: punch → crouching punch, punch → kick, crouching punch → crouching punch, kick → punch. Only punch → crouching punch should (7 ≥ 4 + 3); punch → kick needs 11, the crouching punch has +5 and the kick 0. Then try the first one in the game (F, then hold S and press F again): the second line of the log should be C.PUNCH with combo 2, and crouching punch twice should stay at combo 1.
  3. ★ Set InputBuffer::kWindow to 0. With the clip's script, the second punch should disappear from the log completely (it was pressed 7 steps before Hayate was free, so the press is too old), and the link should only work if you press on exactly the step the first punch's recovery ends.
  4. ★★ Remove the dead step at the end of a move: after setState in the Attack case of Fighter::update, call tryMoves(c.down). With hit stun 16 the punch → punch link should now work, one step earlier (the second hit at step 108 with combo 2), and the rule becomes "advantage at least startup + 2". Decide which version you prefer and fix the comment in moves.cc to match.
  5. ★★ Add a counter hit: if the victim is in the startup frames of a move when hit, add 4 frames of hit stun and draw "COUNTER" on the attacker's side. A punch that hits a kick's 8 startup frames should then link into a kick: the advantage becomes 21 − 10 = +11, at least 8 + 3.
  6. ★★ Give the scene graph a way to find a node's world transform (store parent pointers, or walk from the root and multiply), and attach a short trail effect to the fist socket during active frames. The trail should follow the fist in both facings; note why draw alone never needed parent pointers.
  7. ★★★ Support shear: make Node::draw emit four transformed corners instead of a Sprite (you'll need your own vertex buffer, or a quad entry point in the engine's batch). A parent with scale (1, 0.5) above a tail rotated by 45° should then draw as a parallelogram with its corners exactly where Affine2::apply puts the sprite's corners, matching the orange shape in the shear diagram.

Download the diff

Download the project (ZIP)

ファイル: a/games/fighter/CMakeLists.txt | b/games/fighter/CMakeLists.txt

前新
@@ -3,8 +3,12 @@
3 add_executable(fighter 3 add_executable(fighter
4 src/main.cc 4 src/main.cc
5 src/controls.cc 5 src/controls.cc
    6 src/effects.cc
6 src/fighter.cc 7 src/fighter.cc
7 src/fight_scene.cc) 8 src/fight_scene.cc
    9 src/frame_data.cc
    10 src/moves.cc
    11 src/scene_graph.cc)
8 target_include_directories(fighter PRIVATE src) 12 target_include_directories(fighter PRIVATE src)
9 target_link_libraries(fighter PRIVATE engine) 13 target_link_libraries(fighter PRIVATE engine)
10 enable_warnings(fighter) 14 enable_warnings(fighter)

ファイル: a/games/fighter/README.md | b/games/fighter/README.md

前新
@@ -14,8 +14,17 @@ build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" tar
14 | 前後に歩く / walk | A D | ← → | 14 | 前後に歩く / walk | A D | ← → |
15 | ジャンプ / jump (+ 前・後ろ / forward, back) | W | ↑ | 15 | ジャンプ / jump (+ 前・後ろ / forward, back) | W | ↑ |
16 | しゃがむ / crouch | S | ↓ | 16 | しゃがむ / crouch | S | ↓ |
    17 | パンチ / punch | F | K(テンキー / keypad 1) |
    18 | キック / kick | G | L(テンキー / keypad 2) |
17   19  
18 ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック)。 20 * しゃがみ + パンチ = しゃがみパンチ、しゃがみ + キック = 足払い(下段、ダウン)、空中でパンチかキック = 飛び蹴り(上段)。
19 Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick). 21 Crouch + punch = crouching punch, crouch + kick = sweep (low, knocks down), punch or kick in the air = jump kick (high).
    22 * ガード:相手と反対の方向に入れる。下段はしゃがみガード、飛び蹴りは立ちガードで。
    23 Guard: hold away from the opponent. Block lows crouching and jump kicks standing.
    24 * 技のボタンは8フレーム覚えておく(入力バッファ)。 / Button presses are remembered for 8 frames (input buffer).
20   25  
21 F1 押し合いの箱と状態の表示 / push boxes and states, Esc 終了 / quit. 26 ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。
    27 Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick, A/X punch, B/Y kick).
    28  
    29 F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態 / boxes (hurt blue, hit red, push green,
    30 sockets yellow) and states, Esc 終了 / quit.

ファイル: a/games/fighter/assets/LICENSE.txt | b/games/fighter/assets/LICENSE.txt

前新
@@ -5,3 +5,7 @@ hayate.png/.atlas 1Pのファイター「ハヤテ」(白い道着、128×12
5 38 frames of 128 × 120) (chapter 30) 5 38 frames of 128 × 120) (chapter 30)
6 jin.png/.atlas 2Pのファイター「ジン」(紺の道着、同じコマ割りの色違い) / player 2's fighter "Jin" (indigo gi, the 6 jin.png/.atlas 2Pのファイター「ジン」(紺の道着、同じコマ割りの色違い) / player 2's fighter "Jin" (indigo gi, the
7 same frames in other colors) (chapter 30) 7 same frames in other colors) (chapter 30)
    8 fighter.boxes コマごとの食らい判定・攻撃判定・ソケット(骨格から生成) / per-frame hurt boxes, hit boxes and sockets
    9 (made from the skeleton) (chapter 31)
    10 effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars,
    11 shadow (chapter 31)

ファイル: /dev/null | b/games/fighter/assets/effects.atlas

前新
@@ -0,0 +1,21 @@
    1 # effects: hit/guard sparks, dust, headband tails, dizzy star, shadow (generated by the author's own script)
    2 image effects.png
    3 sprite spark0 1 1 24 24
    4 sprite spark1 27 1 24 24
    5 sprite spark2 53 1 24 24
    6 sprite spark3 79 1 24 24
    7 sprite guard0 1 27 24 24
    8 sprite guard1 27 27 24 24
    9 sprite guard2 53 27 24 24
    10 sprite guard3 79 27 24 24
    11 sprite dust0 105 27 20 12
    12 sprite dust1 1 53 20 12
    13 sprite dust2 23 53 20 12
    14 sprite dust3 45 53 20 12
    15 sprite tail_hayate 67 53 12 4
    16 sprite tail_jin 81 53 12 4
    17 sprite star 95 53 7 7
    18 sprite shadow 1 67 48 10
    19 clip spark 30 once spark0 spark1 spark2 spark3
    20 clip guard 30 once guard0 guard1 guard2 guard3
    21 clip dust 15 once dust0 dust1 dust2 dust3

ファイル: /dev/null | b/games/fighter/assets/effects.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/games/fighter/assets/fighter.boxes

前新
@@ -0,0 +1,283 @@
    1 # 当たり判定のデータ(作者の自作スクリプトが骨格から作る) / hit and hurt box data, made from the skeleton by
    2 # the author's own script. Pixels relative to the feet pivot, facing right, y down.
    3 # hurt <frame> x y w h 食らい判定 / where the fighter can be hit
    4 # hit <frame> x y w h 攻撃判定(有効フレームのコマ) / attack box (active frames)
    5 # socket <frame> <name> x y 部品・エフェクトの取り付け位置 / where parts and effects attach
    6 hurt idle0 -3 -91 16 16
    7 hurt idle0 -10 -83 22 46
    8 hurt idle0 -19 -49 38 50
    9 socket idle0 head 5 -83
    10 socket idle0 knot -4 -87
    11 socket idle0 fist 22 -72
    12 socket idle0 foot 20 -2
    13 hurt idle1 -3 -90 16 16
    14 hurt idle1 -10 -82 22 46
    15 hurt idle1 -20 -48 39 50
    16 socket idle1 head 5 -82
    17 socket idle1 knot -4 -86
    18 socket idle1 fist 22 -70
    19 socket idle1 foot 20 -2
    20 hurt idle2 -3 -89 16 16
    21 hurt idle2 -10 -81 22 46
    22 hurt idle2 -20 -47 39 49
    23 socket idle2 head 5 -81
    24 socket idle2 knot -4 -85
    25 socket idle2 fist 22 -69
    26 socket idle2 foot 20 -2
    27 hurt idle3 -3 -90 16 16
    28 hurt idle3 -10 -82 22 46
    29 hurt idle3 -20 -48 39 50
    30 socket idle3 head 5 -82
    31 socket idle3 knot -4 -86
    32 socket idle3 fist 22 -70
    33 socket idle3 foot 20 -2
    34 hurt walk0 -1 -91 16 16
    35 hurt walk0 -9 -83 23 46
    36 hurt walk0 -18 -49 41 50
    37 socket walk0 head 7 -83
    38 socket walk0 knot -2 -87
    39 socket walk0 fist 22 -72
    40 socket walk0 foot 19 -7
    41 hurt walk1 0 -92 16 16
    42 hurt walk1 -9 -84 23 46
    43 hurt walk1 -23 -51 47 52
    44 socket walk1 head 8 -84
    45 socket walk1 knot -2 -88
    46 socket walk1 fist 22 -73
    47 socket walk1 foot 24 -5
    48 hurt walk2 0 -92 16 16
    49 hurt walk2 -9 -84 23 46
    50 hurt walk2 -24 -51 47 52
    51 socket walk2 head 8 -84
    52 socket walk2 knot -2 -88
    53 socket walk2 fist 22 -73
    54 socket walk2 foot 24 -3
    55 hurt walk3 -1 -91 16 16
    56 hurt walk3 -9 -83 23 46
    57 hurt walk3 -19 -49 37 51
    58 socket walk3 head 7 -83
    59 socket walk3 knot -2 -87
    60 socket walk3 fist 22 -72
    61 socket walk3 foot 19 -2
    62 hurt walk4 -1 -92 16 16
    63 hurt walk4 -10 -84 23 46
    64 hurt walk4 -13 -51 28 52
    65 socket walk4 head 7 -84
    66 socket walk4 knot -2 -88
    67 socket walk4 fist 22 -73
    68 socket walk4 foot 14 -2
    69 hurt walk5 -1 -92 16 16
    70 hurt walk5 -10 -84 23 46
    71 hurt walk5 -13 -51 31 53
    72 socket walk5 head 7 -84
    73 socket walk5 knot -2 -88
    74 socket walk5 fist 22 -73
    75 socket walk5 foot 14 -5
    76 hurt crouch_in 0 -80 16 16
    77 hurt crouch_in -11 -72 25 45
    78 hurt crouch_in -21 -39 45 41
    79 socket crouch_in head 8 -72
    80 socket crouch_in knot -1 -77
    81 socket crouch_in fist 21 -62
    82 socket crouch_in foot 22 -2
    83 hurt crouch 3 -71 16 16
    84 hurt crouch -12 -63 28 44
    85 hurt crouch -22 -31 47 32
    86 socket crouch head 11 -63
    87 socket crouch knot 2 -68
    88 socket crouch fist 22 -53
    89 socket crouch foot 23 -2
    90 hurt jump_up -2 -93 16 16
    91 hurt jump_up -9 -85 22 46
    92 hurt jump_up -13 -51 41 42
    93 socket jump_up head 6 -85
    94 socket jump_up knot -3 -89
    95 socket jump_up fist 19 -81
    96 socket jump_up foot 14 -19
    97 hurt jump_tuck 6 -93 16 16
    98 hurt jump_tuck -9 -85 28 44
    99 hurt jump_tuck -8 -61 35 36
    100 socket jump_tuck head 14 -85
    101 socket jump_tuck knot 5 -90
    102 socket jump_tuck fist 18 -76
    103 socket jump_tuck foot 18 -32
    104 hurt jump_down -4 -94 16 16
    105 hurt jump_down -9 -85 21 46
    106 hurt jump_down -15 -51 38 50
    107 socket jump_down head 4 -86
    108 socket jump_down knot -5 -89
    109 socket jump_down fist 21 -78
    110 socket jump_down foot 14 -7
    111 hurt punch0 -5 -92 16 16
    112 hurt punch0 -10 -83 21 46
    113 hurt punch0 -19 -49 38 50
    114 socket punch0 head 3 -84
    115 socket punch0 knot -6 -87
    116 socket punch0 fist 16 -72
    117 socket punch0 foot 20 -2
    118 hurt punch1 6 -89 16 16
    119 hurt punch1 -6 -81 26 45
    120 hurt punch1 -19 -48 41 50
    121 hurt punch1 22 -74 26 10
    122 hit punch1 37 -75 14 10
    123 socket punch1 head 14 -81
    124 socket punch1 knot 5 -85
    125 socket punch1 fist 44 -70
    126 socket punch1 foot 22 -2
    127 hurt punch2 1 -91 16 16
    128 hurt punch2 -8 -83 23 46
    129 hurt punch2 -19 -49 39 51
    130 hurt punch2 15 -77 21 21
    131 socket punch2 head 9 -83
    132 socket punch2 knot 0 -87
    133 socket punch2 fist 32 -73
    134 socket punch2 foot 21 -2
    135 hurt kick0 -11 -93 16 16
    136 hurt kick0 -12 -84 18 46
    137 hurt kick0 -18 -57 42 59
    138 socket kick0 head -3 -85
    139 socket kick0 knot -12 -88
    140 socket kick0 fist 17 -76
    141 socket kick0 foot 17 -29
    142 hurt kick1 -20 -93 16 16
    143 hurt kick1 -18 -85 26 45
    144 hurt kick1 -18 -52 24 53
    145 hurt kick1 -3 -66 53 22
    146 hit kick1 39 -70 18 14
    147 socket kick1 head -12 -85
    148 socket kick1 knot -22 -86
    149 socket kick1 fist 10 -82
    150 socket kick1 foot 50 -64
    151 hurt kick2 -14 -93 16 16
    152 hurt kick2 -14 -84 19 46
    153 hurt kick2 -18 -50 21 51
    154 hurt kick2 -6 -56 31 32
    155 socket kick2 head -6 -85
    156 socket kick2 knot -15 -87
    157 socket kick2 fist 17 -78
    158 socket kick2 foot 25 -28
    159 hurt sweep0 3 -69 16 16
    160 hurt sweep0 -13 -61 29 44
    161 hurt sweep0 -23 -30 49 32
    162 socket sweep0 head 11 -61
    163 socket sweep0 knot 2 -65
    164 socket sweep0 fist 21 -48
    165 socket sweep0 foot 27 -2
    166 hurt sweep1 12 -57 16 16
    167 hurt sweep1 -10 -50 33 41
    168 hurt sweep1 -21 -21 31 29
    169 hurt sweep1 -5 -21 54 19
    170 hit sweep1 37 -11 20 10
    171 socket sweep1 head 20 -49
    172 socket sweep1 knot 12 -55
    173 socket sweep1 fist 30 -9
    174 socket sweep1 foot 49 -6
    175 hurt sweep2 6 -65 16 16
    176 hurt sweep2 -12 -58 31 43
    177 hurt sweep2 -22 -27 31 29
    178 hurt sweep2 -7 -28 41 29
    179 socket sweep2 head 14 -57
    180 socket sweep2 knot 6 -63
    181 socket sweep2 fist 26 -42
    182 socket sweep2 foot 35 -2
    183 hurt jkick0 4 -94 16 16
    184 hurt jkick0 -9 -86 27 45
    185 hurt jkick0 -8 -64 33 37
    186 socket jkick0 head 12 -86
    187 socket jkick0 knot 4 -90
    188 socket jkick0 fist 15 -78
    189 socket jkick0 foot 20 -34
    190 hurt jkick1 -14 -97 16 16
    191 hurt jkick1 -14 -88 20 46
    192 hurt jkick1 -10 -54 31 25
    193 hurt jkick1 -5 -54 46 36
    194 hit jkick1 29 -30 18 14
    195 socket jkick1 head -6 -89
    196 socket jkick1 knot -16 -91
    197 socket jkick1 fist 12 -82
    198 socket jkick1 foot 40 -25
    199 hurt cpunch0 1 -72 16 16
    200 hurt cpunch0 -12 -64 27 45
    201 hurt cpunch0 -22 -31 47 32
    202 socket cpunch0 head 9 -64
    203 socket cpunch0 knot 1 -68
    204 socket cpunch0 fist 17 -52
    205 socket cpunch0 foot 23 -2
    206 hurt cpunch1 8 -70 16 16
    207 hurt cpunch1 -9 -62 30 43
    208 hurt cpunch1 -21 -31 49 32
    209 hurt cpunch1 22 -54 27 9
    210 hit cpunch1 37 -55 14 10
    211 socket cpunch1 head 16 -62
    212 socket cpunch1 knot 8 -67
    213 socket cpunch1 fist 44 -50
    214 socket cpunch1 foot 24 -2
    215 hurt cpunch2 4 -71 16 16
    216 hurt cpunch2 -11 -63 28 44
    217 hurt cpunch2 -22 -31 48 33
    218 hurt cpunch2 15 -56 21 21
    219 socket cpunch2 head 12 -63
    220 socket cpunch2 knot 4 -68
    221 socket cpunch2 fist 32 -52
    222 socket cpunch2 foot 23 -2
    223 hurt block -16 -92 16 16
    224 hurt block -16 -83 19 46
    225 hurt block -20 -49 37 50
    226 socket block head -8 -84
    227 socket block knot -17 -87
    228 socket block fist 13 -86
    229 socket block foot 18 -2
    230 hurt cblock -4 -73 16 16
    231 hurt cblock -13 -65 24 46
    232 hurt cblock -22 -31 46 32
    233 socket cblock head 4 -65
    234 socket cblock knot -4 -70
    235 socket cblock fist 14 -63
    236 socket cblock foot 22 -2
    237 hurt hit0 -25 -90 16 16
    238 hurt hit0 -23 -82 25 45
    239 hurt hit0 -19 -49 37 50
    240 socket hit0 head -17 -82
    241 socket hit0 knot -26 -81
    242 socket hit0 fist 10 -65
    243 socket hit0 foot 19 -2
    244 hurt hit1 -33 -87 16 16
    245 hurt hit1 -30 -79 30 43
    246 hurt hit1 -19 -48 38 50
    247 socket hit1 head -25 -79
    248 socket hit1 knot -34 -76
    249 socket hit1 fist 4 -61
    250 socket hit1 foot 20 -3
    251 hurt chit -12 -75 16 16
    252 hurt chit -15 -66 19 46
    253 hurt chit -21 -32 43 34
    254 socket chit head -4 -67
    255 socket chit knot -14 -67
    256 socket chit fist 8 -47
    257 socket chit foot 22 -2
    258 hurt ko0 -40 -68 16 16
    259 hurt ko0 -33 -65 43 31
    260 hurt ko0 -4 -69 36 34
    261 socket ko0 head -32 -60
    262 socket ko0 knot -40 -54
    263 socket ko0 fist -28 -73
    264 socket ko0 foot 31 -57
    265 hurt ko1 -38 -15 87 14
    266 socket ko1 head -33 -8
    267 socket ko1 knot -36 1
    268 socket ko1 fist -46 -1
    269 socket ko1 foot 45 -11
    270 hurt win0 -9 -93 16 16
    271 hurt win0 -9 -84 16 46
    272 hurt win0 -16 -50 33 51
    273 socket win0 head -1 -85
    274 socket win0 knot -11 -86
    275 socket win0 fist 20 -98
    276 socket win0 foot 18 -2
    277 hurt win1 -10 -94 16 16
    278 hurt win1 -11 -85 18 46
    279 hurt win1 -16 -51 33 52
    280 socket win1 head -2 -86
    281 socket win1 knot -12 -86
    282 socket win1 fist 19 -98
    283 socket win1 foot 18 -2

ファイル: a/games/fighter/src/controls.cc | b/games/fighter/src/controls.cc

前新
@@ -5,25 +5,38 @@ namespace {
5   5  
6 // 行動の名前(プレイヤーごと) / action names per player 6 // 行動の名前(プレイヤーごと) / action names per player
7 struct ActionNames { 7 struct ActionNames {
8 const char *left, *right, *up, *down; 8 const char *left, *right, *up, *down, *punch, *kick;
9 }; 9 };
10 constexpr ActionNames kActions[2] = { 10 constexpr ActionNames kActions[2] = {
11 {"p1.left", "p1.right", "p1.up", "p1.down"}, 11 {"p1.left", "p1.right", "p1.up", "p1.down", "p1.punch", "p1.kick"},
12 {"p2.left", "p2.right", "p2.up", "p2.down"}, 12 {"p2.left", "p2.right", "p2.up", "p2.down", "p2.punch", "p2.kick"},
13 }; 13 };
14   14  
15 // ゲームパッド(GLFW 3.3以上のSDL互換マッピング):十字キーか左スティック。つながっていなければ何もしない 15 // ゲームパッド(GLFW 3.3以上のSDL互換マッピング):十字キーか左スティック、A/Xで突き、B/Yで蹴り。
16 // A gamepad (GLFW 3.3+'s SDL-style mapping): the d-pad or the left stick. Does nothing when none is connected 16 // つながっていなければ何もしない
17 void addGamepad(int player, Controls &c) { 17 // A gamepad (GLFW 3.3+'s SDL-style mapping): d-pad or left stick, A/X punch, B/Y kick. Does nothing when none is
    18 // connected
    19 void addGamepad(int player, Controls &c, GamepadEdges &edges) {
18 int jid = GLFW_JOYSTICK_1 + player; 20 int jid = GLFW_JOYSTICK_1 + player;
19 GLFWgamepadstate pad; 21 GLFWgamepadstate pad;
20 if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) return; 22 if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) {
    23 edges = {};
    24 return;
    25 }
    26 auto down = [&](int b) { return pad.buttons[b] == GLFW_PRESS; };
21 constexpr float kDeadZone = 0.5f; 27 constexpr float kDeadZone = 0.5f;
22 float x = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_X], y = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]; 28 float x = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_X], y = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_Y];
23 c.left |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT] == GLFW_PRESS || x < -kDeadZone; 29 c.left |= down(GLFW_GAMEPAD_BUTTON_DPAD_LEFT) || x < -kDeadZone;
24 c.right |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT] == GLFW_PRESS || x > kDeadZone; 30 c.right |= down(GLFW_GAMEPAD_BUTTON_DPAD_RIGHT) || x > kDeadZone;
25 c.up |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP] == GLFW_PRESS || y < -kDeadZone; 31 c.up |= down(GLFW_GAMEPAD_BUTTON_DPAD_UP) || y < -kDeadZone;
26 c.down |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN] == GLFW_PRESS || y > kDeadZone; 32 c.down |= down(GLFW_GAMEPAD_BUTTON_DPAD_DOWN) || y > kDeadZone;
    33 // GLFWのゲームパッドは状態だけ:押した瞬間は前のステップと比べて作る / GLFW gamepads only give states: presses
    34 // come from comparing with the last step
    35 bool punch = down(GLFW_GAMEPAD_BUTTON_A) || down(GLFW_GAMEPAD_BUTTON_X);
    36 bool kick = down(GLFW_GAMEPAD_BUTTON_B) || down(GLFW_GAMEPAD_BUTTON_Y);
    37 c.punch |= punch && !edges.punch;
    38 c.kick |= kick && !edges.kick;
    39 edges = {punch, kick};
27 } 40 }
28   41  
29 } // namespace 42 } // namespace
@@ -36,17 +49,23 @@ void bindPlayerActions(Input &input) {
36 input.bind(a.right, {InputBinding::key(k.right)}); 49 input.bind(a.right, {InputBinding::key(k.right)});
37 input.bind(a.up, {InputBinding::key(k.up)}); 50 input.bind(a.up, {InputBinding::key(k.up)});
38 input.bind(a.down, {InputBinding::key(k.down)}); 51 input.bind(a.down, {InputBinding::key(k.down)});
    52 input.bind(a.punch, {InputBinding::key(k.punch)});
    53 input.bind(a.kick, {InputBinding::key(k.kick)});
    54 if (k.punchAlt >= 0) input.bind(a.punch, {InputBinding::key(k.punchAlt)});
    55 if (k.kickAlt >= 0) input.bind(a.kick, {InputBinding::key(k.kickAlt)});
39 } 56 }
40 } 57 }
41   58  
42 Controls readControls(const Input &input, int player) { 59 Controls readControls(const Input &input, int player, GamepadEdges &pad) {
43 const ActionNames &a = kActions[player]; 60 const ActionNames &a = kActions[player];
44 Controls c; 61 Controls c;
45 c.left = input.actionHeld(a.left); 62 c.left = input.actionHeld(a.left);
46 c.right = input.actionHeld(a.right); 63 c.right = input.actionHeld(a.right);
47 c.up = input.actionHeld(a.up); 64 c.up = input.actionHeld(a.up);
48 c.down = input.actionHeld(a.down); 65 c.down = input.actionHeld(a.down);
49 addGamepad(player, c); 66 c.punch = input.actionPressed(a.punch);
    67 c.kick = input.actionPressed(a.kick);
    68 addGamepad(player, c, pad);
50 // 左右同時は「どちらでもない」(格闘ゲームの決まり:SOCD) / left + right together = neither (the fighting-game 69 // 左右同時は「どちらでもない」(格闘ゲームの決まり:SOCD) / left + right together = neither (the fighting-game
51 // rule for simultaneous opposite directions, "SOCD") 70 // rule for simultaneous opposite directions, "SOCD")
52 if (c.left && c.right) c.left = c.right = false; 71 if (c.left && c.right) c.left = c.right = false;

ファイル: a/games/fighter/src/controls.hh | b/games/fighter/src/controls.hh

前新
@@ -4,27 +4,34 @@
4   4  
5 #include "engine/input.hh" 5 #include "engine/input.hh"
6   6  
7 // 1ステップ分の入力。方向は押している間、ファイターはこれだけを見る(キーもパッドも知らない) 7 // 1ステップ分の入力。方向は押している間、ボタンは押した瞬間だけ。ファイターはこれだけを見る
8 // One step of input. Directions are "held". The fighter only sees this (it knows nothing about keys or pads) 8 // One step of input. Directions are "held", buttons are "pressed this step". The fighter only sees this
9 struct Controls { 9 struct Controls {
10 bool left = false, right = false, up = false, down = false; 10 bool left = false, right = false, up = false, down = false;
    11 bool punch = false, kick = false;
11 }; 12 };
12   13  
13 // 一人分のキー(GLFW_KEY_…) / one player's keys (GLFW_KEY_...) 14 // 一人分のキー(GLFW_KEY_…、-1 = なし) / one player's keys (GLFW_KEY_..., -1 = none)
14 struct PlayerKeys { 15 struct PlayerKeys {
15 int left, right, up, down; 16 int left, right, up, down, punch, kick, punchAlt, kickAlt;
16 }; 17 };
17   18  
18 // 1P:WASD、2P:矢印キー / 1P: WASD, 2P: the arrow keys 19 // 1P:WASD + F G、2P:矢印キー + K L(テンキーの1 2でも) / 1P: WASD + F G, 2P: arrow keys + K L (or keypad 1 2)
19 constexpr PlayerKeys kPlayerKeys[2] = { 20 constexpr PlayerKeys kPlayerKeys[2] = {
20 {GLFW_KEY_A, GLFW_KEY_D, GLFW_KEY_W, GLFW_KEY_S}, 21 {GLFW_KEY_A, GLFW_KEY_D, GLFW_KEY_W, GLFW_KEY_S, GLFW_KEY_F, GLFW_KEY_G, -1, -1},
21 {GLFW_KEY_LEFT, GLFW_KEY_RIGHT, GLFW_KEY_UP, GLFW_KEY_DOWN}, 22 {GLFW_KEY_LEFT, GLFW_KEY_RIGHT, GLFW_KEY_UP, GLFW_KEY_DOWN, GLFW_KEY_K, GLFW_KEY_L, GLFW_KEY_KP_1, GLFW_KEY_KP_2},
22 }; 23 };
23   24  
24 // 二人分の行動をInputに登録する("p1.left"、"p2.up"…) / registers both players' actions with Input ("p1.left", 25 // ゲームパッドのボタンの前のステップの状態(押した瞬間を作るため) / the gamepad buttons' state in the last step
25 // "p2.up"...) 26 // (to detect presses)
    27 struct GamepadEdges {
    28 bool punch = false, kick = false;
    29 };
    30  
    31 // 二人分の行動をInputに登録する("p1.left"、"p2.punch"…) / registers both players' actions with Input ("p1.left",
    32 // "p2.punch"...)
26 void bindPlayerActions(Input &input); 33 void bindPlayerActions(Input &input);
27   34  
28 // キーボードの行動と、ゲームパッド(GLFW_JOYSTICK_1 + player)を合わせて読む。playerは0か1 35 // キーボードの行動と、ゲームパッド(GLFW_JOYSTICK_1 + player)を合わせて読む。playerは0か1
29 // Reads the keyboard actions together with the gamepad (GLFW_JOYSTICK_1 + player). player is 0 or 1 36 // Reads the keyboard actions together with the gamepad (GLFW_JOYSTICK_1 + player). player is 0 or 1
30 Controls readControls(const Input &input, int player); 37 Controls readControls(const Input &input, int player, GamepadEdges &pad);

ファイル: /dev/null | b/games/fighter/src/effects.cc

前新
@@ -0,0 +1,49 @@
    1 // エフェクト / effects
    2 #include "effects.hh"
    3  
    4 #include <algorithm>
    5  
    6 Effects::Effects(const SpriteSheet &s)
    7 : sheet(s), sparkClip(s.clip("spark")), guardClip(s.clip("guard")), dustClip(s.clip("dust")) {}
    8  
    9 void Effects::spawn(const AnimationClip *clip, Vec2 at, float rotation, Vec2 scale, Vec2 velocity, float layer) {
    10 if (!clip) return;
    11 Node &n = root.add("effect");
    12 n.position = at;
    13 n.rotation = rotation;
    14 n.scale = scale;
    15 n.sprite = sheet.sprite(clip->frames[0], {0.0f, 0.0f}, {0.5f, 0.5f});
    16 n.sprite->layer = layer;
    17 Live l{&n, {}, velocity};
    18 l.animator.play(clip, true);
    19 live.push_back(l);
    20 }
    21  
    22 void Effects::spark(Vec2 at, bool guard, bool heavy) {
    23 // 火花は少し回して毎回違って見せる(加算ではなく普通の半透明:ピクセルアートの色のまま)
    24 // Sparks are turned a little so they differ each time (ordinary alpha, not additive: the pixel-art colors stay)
    25 float s = heavy ? 2.0f : 1.0f;
    26 spawn(guard ? guardClip : sparkClip, at, rng.range(0.0f, 1.57f), {s, s}, {0.0f, 0.0f}, 6.0f);
    27 }
    28  
    29 void Effects::dust(Vec2 at, float facing) {
    30 spawn(dustClip, at + Vec2{-facing * 10.0f, -5.0f}, 0.0f, {-facing, 1.0f}, {-facing * 40.0f, -8.0f}, 1.8f);
    31 spawn(dustClip, at + Vec2{facing * 10.0f, -5.0f}, 0.0f, {facing, 1.0f}, {facing * 25.0f, -6.0f}, 1.8f);
    32 }
    33  
    34 void Effects::update(float dt) {
    35 for (Live &l : live) {
    36 l.animator.update(dt);
    37 l.node->position += l.velocity * dt;
    38 if (!l.animator.finished()) l.node->sprite->uv = sheet.uv(l.animator.frame());
    39 }
    40 // 終わったものを外す(ノードもlistも) / remove finished ones (the node and the list entry)
    41 for (Live &l : live)
    42 if (l.animator.finished()) root.remove(l.node);
    43 std::erase_if(live, [](const Live &l) { return l.animator.finished(); });
    44 }
    45  
    46 void Effects::clear() {
    47 root.children.clear();
    48 live.clear();
    49 }

ファイル: /dev/null | b/games/fighter/src/effects.hh

前新
@@ -0,0 +1,37 @@
    1 // エフェクト:ヒットの火花、ガードの火花、砂ぼこり。どれもシーングラフのノード(effectsの根の子)
    2 // Effects: hit sparks, guard sparks, dust. Each is a scene-graph node (a child of the effects root)
    3 #pragma once
    4  
    5 #include "scene_graph.hh"
    6  
    7 #include "engine/animation.hh"
    8 #include "engine/rng.hh"
    9 #include "engine/sprite_sheet.hh"
    10  
    11 #include <vector>
    12  
    13 class Effects {
    14 public:
    15 explicit Effects(const SpriteSheet &sheet);
    16 // 当たった場所に火花。heavyなら大きく / a spark where the hit landed; bigger when heavy
    17 void spark(Vec2 at, bool guard, bool heavy);
    18 // 足元に砂ぼこり(facingの後ろへ流れる) / dust at the feet (drifting behind `facing`)
    19 void dust(Vec2 at, float facing);
    20 void update(float dt);
    21 void draw(SpriteBatch &batch) const { root.draw(batch); }
    22 void clear();
    23  
    24 private:
    25 struct Live {
    26 Node *node;
    27 Animator animator;
    28 Vec2 velocity;
    29 };
    30 void spawn(const AnimationClip *clip, Vec2 at, float rotation, Vec2 scale, Vec2 velocity, float layer);
    31  
    32 const SpriteSheet &sheet;
    33 const AnimationClip *sparkClip, *guardClip, *dustClip;
    34 Node root{"effects"};
    35 std::vector<Live> live;
    36 Rng rng{31}; // 火花の向き(固定の種:毎回同じ) / spark angles (fixed seed: identical every run)
    37 };

ファイル: a/games/fighter/src/fight_scene.cc | b/games/fighter/src/fight_scene.cc

前新
@@ -1,4 +1,5 @@
1 // 対戦の場面(第30章:二人が動き回る練習モード) / the fight scene (chapter 30: a training mode where both move) 1 // 対戦の場面(第31章:技の当たり、ヒットストップ、体力、エフェクト。KOすると練習を仕切り直す)
    2 // The fight scene (chapter 31: hits, hit stop, health, effects; a KO restarts the training)
2 #include "fight_scene.hh" 3 #include "fight_scene.hh"
3   4  
4 #include "engine/collision.hh" 5 #include "engine/collision.hh"
@@ -7,20 +8,21 @@
7 #include <cmath> 8 #include <cmath>
8 #include <cstdio> 9 #include <cstdio>
9 #include <string> 10 #include <string>
    11 #include <string_view>
10   12  
11 namespace { 13 namespace {
12   14  
13 // 画面の端(押し合いの箱がこの外に出ない) / the stage edges (push boxes never leave them)    
14 constexpr float kStageLeft = 16.0f; 15 constexpr float kStageLeft = 16.0f;
15 constexpr float kStageRight = 624.0f; 16 constexpr float kStageRight = 624.0f;
    17 constexpr Vec2 kStart[2] = {{200.0f, kGroundY}, {440.0f, kGroundY}};
16   18  
17 // 道場の色 / the dojo's colors    
18 constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff); 19 constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff);
19 constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff); 20 constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff);
20 constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff); 21 constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff);
21 constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff); 22 constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff);
22 constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff); 23 constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff);
23 constexpr Vec4 kOutline = hexColor(0x1b1726ff); 24 constexpr Vec4 kOutline = hexColor(0x1b1726ff);
    25 constexpr Vec4 kText = hexColor(0xfff4d8ff), kGold = hexColor(0xf2c14eff);
24   26  
25 void clampToStage(Fighter &f) { 27 void clampToStage(Fighter &f) {
26 Rect b = f.pushbox(); 28 Rect b = f.pushbox();
@@ -28,34 +30,119 @@ void clampToStage(Fighter &f) {
28 if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight; 30 if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight;
29 } 31 }
30   32  
    33 bool atWall(const Fighter &f) {
    34 Rect b = f.pushbox();
    35 return b.left() <= kStageLeft + 0.5f || b.right() >= kStageRight - 0.5f;
    36 }
    37  
    38 // 二つの箱の重なり(火花を出す場所) / the overlap of two boxes (where the spark goes)
    39 Rect intersection(const Rect &a, const Rect &b) {
    40 float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top());
    41 float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom());
    42 return {l, t, r - l, bt - t};
    43 }
    44  
    45 // 大きな文字(K.O.など):8方向に輪郭を描いてから本体 / big text (K.O. and so on): an outline in 8 directions, then
    46 // the text itself
    47 void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale) {
    48 Vec2 size = font.measure(text, scale);
    49 Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)};
    50 TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = 11.0f};
    51 for (Vec2 d : {Vec2{-2, -2}, Vec2{0, -2}, Vec2{2, -2}, Vec2{-2, 0}, Vec2{2, 0}, Vec2{-2, 2}, Vec2{0, 2}, Vec2{2, 2},
    52 Vec2{3, 4}, Vec2{0, 4}})
    53 font.draw(b, text, at + d, s);
    54 s.color = color;
    55 s.layer = 11.5f;
    56 font.draw(b, text, at, s);
    57 }
    58  
    59 // 体力ゲージ:中央側に寄せて、外側から減る。白い「跡」は少し遅れて追いかける
    60 // A health bar: anchored at the center side, it drains from the outer end. The white "trail" follows a little later
    61 void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) {
    62 b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f);
    63 b.drawRect(r, hexColor(0x4a2434ff), 10.1f);
    64 auto part = [&](float amount) {
    65 float w = std::round(r.w * std::clamp(amount / static_cast<float>(kMaxHealth), 0.0f, 1.0f));
    66 return rightSide ? Rect{r.x, r.y, w, r.h} : Rect{r.right() - w, r.y, w, r.h};
    67 };
    68 b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f);
    69 bool low = health <= kMaxHealth * 0.25f;
    70 Rect h = part(health);
    71 b.drawRect(h, low ? hexColor(0xe8483cff) : kGold, 10.3f);
    72 b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f);
    73 b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f);
    74 }
    75  
31 } // namespace 76 } // namespace
32   77  
33 FightScene::FightScene(Game &game) 78 FightScene::FightScene(Game &game)
34 : g(game), camera(Camera2D::screen(kViewSize)), 79 : g(game), camera(Camera2D::screen(kViewSize)),
35 fighters{Fighter(*game.fighters[0], "HAYATE", {200.0f, kGroundY}, 1.0f), 80 fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f),
36 Fighter(*game.fighters[1], "JIN", {440.0f, kGroundY}, -1.0f)} {} 81 Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)},
    82 effects(*game.effects) {}
    83  
    84 void FightScene::resetRound() {
    85 fighters[0].reset(kStart[0], 1.0f);
    86 fighters[1].reset(kStart[1], -1.0f);
    87 effects.clear();
    88 for (int i = 0; i < 2; ++i) {
    89 trail[i] = kMaxHealth;
    90 comboTime[i] = 0;
    91 }
    92 hitstop = shake = koTime = 0;
    93 victim = -1;
    94 }
37   95  
38 void FightScene::update(float dt) { 96 void FightScene::update(float dt) {
    97 ++steps;
39 Input &in = g.input; 98 Input &in = g.input;
40 if (in.pressed(GLFW_KEY_ESCAPE)) { 99 if (in.pressed(GLFW_KEY_ESCAPE)) {
41 scenes().pop(); // 最後のシーン:終了 / the last scene: quit 100 scenes().pop();
42 return; 101 return;
43 } 102 }
44 if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; 103 if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes;
45   104  
46 // 二人の入力を先に全部読み、相手の位置もステップの最初の値を使う:1Pを先に動かしても2Pが得をしない 105 Controls controls[2] = {readControls(in, 0, pads[0]), readControls(in, 1, pads[1])};
47 // Read both inputs first and use the opponents' positions from the start of the step: updating 1P first gives 106 // バッファはヒットストップ中も記録する:止まっている間に押した技が、動き出した瞬間に出る
48 // neither player an advantage 107 // The buffers record during hit stop too: a move pressed while frozen comes out the moment things move again
49 Controls controls[2] = {readControls(in, 0), readControls(in, 1)}; 108 for (int i = 0; i < 2; ++i) {
    109 fighters[i].buffer.record(controls[i]);
    110 fighters[i].savePrevious(); // 止まっていても前の位置 = 今(補間で震えない) / even when frozen (no wobble)
    111 }
    112 effects.update(dt);
    113 for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1);
    114 shake = std::max(0, shake - 1);
    115 // ヒットストップ:当たった瞬間、数フレーム全部止める(重さが伝わる)。火花のアニメーションだけ進む
    116 // Hit stop: everything freezes for a few frames on contact (it sells the impact). Only the sparks keep animating
    117 if (hitstop > 0) {
    118 --hitstop;
    119 return;
    120 }
    121 victim = -1;
    122  
50 float startX[2] = {fighters[0].position.x, fighters[1].position.x}; 123 float startX[2] = {fighters[0].position.x, fighters[1].position.x};
51 for (Fighter &f : fighters) f.savePrevious(); 124 bool threat[2];
52 for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i]); 125 for (int i = 0; i < 2; ++i) {
    126 // 相手が近く(150ピクセル)で技の発生か持続にいる / the opponent is in a move's startup or active frames nearby
    127 const Fighter &o = fighters[1 - i];
    128 MovePhase p = o.phase();
    129 threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f;
    130 }
    131 for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]);
53 separate(); 132 separate();
    133 resolveHits();
    134 for (Fighter &f : fighters)
    135 if (f.landed) effects.dust(f.position, f.facing);
    136  
    137 // 体力の跡:0.5秒待ってから減る / the health trail: waits half a second, then drains
    138 for (int i = 0; i < 2; ++i) {
    139 if (trailDelay[i] > 0) --trailDelay[i];
    140 else trail[i] = std::max(static_cast<float>(fighters[i].health), trail[i] - 0.6f);
    141 }
    142 // 練習:KOから3秒で仕切り直し / training: restart 3 s after a KO
    143 if (koTime > 0 && ++koTime > 180) resetRound();
54 } 144 }
55   145  
56 // 押し合い:箱が重なったら半分ずつ離す。片方が壁で止まったら、もう片方がその分も下がる    
57 // Pushing: overlapping push boxes are moved apart by half the overlap each. If one is stopped by a wall, the other    
58 // takes the rest    
59 void FightScene::separate() { 146 void FightScene::separate() {
60 Fighter &a = fighters[0], &b = fighters[1]; 147 Fighter &a = fighters[0], &b = fighters[1];
61 clampToStage(a); 148 clampToStage(a);
@@ -63,26 +150,94 @@ void FightScene::separate() {
63 Rect ra = a.pushbox(), rb = b.pushbox(); 150 Rect ra = a.pushbox(), rb = b.pushbox();
64 if (!overlaps(ra, rb)) return; 151 if (!overlaps(ra, rb)) return;
65 float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left()); 152 float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left());
66 float dir = a.position.x < b.position.x ? -1.0f : a.position.x > b.position.x ? 1.0f : -a.facing; // aの動く向き / 153 float dir = a.position.x < b.position.x ? -1.0f : a.position.x > b.position.x ? 1.0f : -a.facing;
67 // a's direction    
68 a.position.x += dir * overlap * 0.5f; 154 a.position.x += dir * overlap * 0.5f;
69 b.position.x -= dir * overlap * 0.5f; 155 b.position.x -= dir * overlap * 0.5f;
70 float ax = a.position.x, bx = b.position.x; 156 float ax = a.position.x, bx = b.position.x;
71 clampToStage(a); 157 clampToStage(a);
72 clampToStage(b); 158 clampToStage(b);
73 // 壁が押し返した分を先に両方覚えてから、相手に渡す / remember both wall corrections first, then pass each one on    
74 float da = a.position.x - ax, db = b.position.x - bx; 159 float da = a.position.x - ax, db = b.position.x - bx;
75 b.position.x += da; 160 b.position.x += da;
76 a.position.x += db; 161 a.position.x += db;
77 } 162 }
78   163  
    164 // 当たり判定:攻撃側の攻撃判定(持続フレーム)と相手の食らい判定が重なったら当たり。
    165 // 先に二人分を調べてから当てる:同時に当たったら相打ち
    166 // Hit detection: the attacker's hit box (active frames) overlapping one of the opponent's hurt boxes is a hit.
    167 // Both directions are checked first and applied afterwards: simultaneous hits trade
    168 void FightScene::resolveHits() {
    169 // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう
    170 // The move is remembered here: in a trade the first takeHit clears the second attacker's move
    171 struct Contact {
    172 int attacker;
    173 const MoveData *move;
    174 Rect where;
    175 bool blocked;
    176 };
    177 Contact contacts[2];
    178 int count = 0;
    179 for (int i = 0; i < 2; ++i) {
    180 Fighter &a = fighters[i], &v = fighters[1 - i];
    181 std::optional<Rect> hit = a.activeHitbox();
    182 if (!hit) continue;
    183 for (const Rect &hurt : v.hurtboxes()) {
    184 if (!overlaps(*hit, hurt)) continue;
    185 contacts[count++] = {i, a.move, intersection(*hit, hurt), v.canBlock(a.move->height, a.position.x)};
    186 break;
    187 }
    188 }
    189 float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end)
    190 for (int c = 0; c < count; ++c) {
    191 int i = contacts[c].attacker;
    192 Fighter &a = fighters[i], &v = fighters[1 - i];
    193 const MoveData &m = *contacts[c].move;
    194 a.confirmHit();
    195 bool wasHit = v.state == FighterState::Hitstun;
    196 HitResult r = v.takeHit(m, a.facing, contacts[c].blocked);
    197 // 壁際:相手が下がれないので自分が下がる(壁で永久に固めさせない) / at the wall the opponent cannot move back,
    198 // so the attacker is pushed back instead (no endless corner pressure)
    199 if (atWall(v)) push[i] = m.knockback * 0.7f;
    200 bool blocked = r == HitResult::Blocked;
    201 int stop = blocked ? m.hitstop - 3 : m.hitstop;
    202 if (r == HitResult::KO) {
    203 stop = 40;
    204 koTime = 1;
    205 }
    206 hitstop = std::max(hitstop, stop);
    207 victim = 1 - i;
    208 top = i;
    209 bool heavy = m.damage >= 10 || r == HitResult::KO;
    210 if (heavy && !blocked) shake = stop;
    211 Rect w = contacts[c].where;
    212 effects.spark(w.centre(), blocked, heavy);
    213 // 記録(台本で動かしたときの確認に) / a log line (to check scripted runs)
    214 static const char *const kResult[] = {"hit", "blocked", "KO"};
    215 printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name,
    216 v.name.c_str(), kResult[static_cast<int>(r)], v.health, blocked ? 0 : v.combo, stop);
    217 if (!blocked) {
    218 trailDelay[1 - i] = 30;
    219 if (wasHit && v.combo >= 2) {
    220 comboHits[i] = v.combo;
    221 comboTime[i] = 90;
    222 }
    223 }
    224 }
    225 // 押し返しは全部のノックバックの後:相打ちで受けたノックバックを消さず、どちらの接触が先でも結果は同じ
    226 // Push-backs come after every knockback: in a trade they never cancel the knockback the attacker just took, and
    227 // the result is the same whichever contact was applied first
    228 for (int i = 0; i < 2; ++i)
    229 if (push[i] > 0.0f) fighters[i].pushBack(push[i]);
    230 }
    231  
79 void FightScene::drawBackground() { 232 void FightScene::drawBackground() {
80 SpriteBatch &b = g.batch; 233 SpriteBatch &b = g.batch;
    234 // 画面より8ピクセルずつ広く描く:画面が揺れても端に隙間ができない / drawn 8 pixels wider than the view on every side,
    235 // so the screen shake never opens a gap at the edges
81 // 梁と漆喰の壁 / beams and the plaster wall 236 // 梁と漆喰の壁 / beams and the plaster wall
82 b.drawRect({0, 0, 640, 360}, kPlaster); 237 b.drawRect({-8, -8, 656, 376}, kPlaster);
83 b.drawRect({0, 0, 640, 34}, kBeam); 238 b.drawRect({-8, -8, 656, 42}, kBeam);
84 b.drawRect({0, 34, 640, 3}, kBeamLight); 239 b.drawRect({-8, 34, 656, 3}, kBeamLight);
85 b.drawRect({0, 37, 640, 4}, kPlasterShade); 240 b.drawRect({-8, 37, 656, 4}, kPlasterShade);
86 for (float x = 0; x < 640; x += 160) { 241 for (float x = 0; x < 640; x += 160) {
87 b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars 242 b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars
88 b.drawRect({x + 9, 37, 3, 200}, kBeamLight); 243 b.drawRect({x + 9, 37, 3, 200}, kBeamLight);
@@ -106,15 +261,16 @@ void FightScene::drawBackground() {
106 g.pixel.draw(b, "習", {244, 122}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); 261 g.pixel.draw(b, "習", {244, 122}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre});
107 b.drawRect({236, 166, 16, 8}, hexColor(0xc83c3cff)); // 落款 / the seal 262 b.drawRect({236, 166, 16, 8}, hexColor(0xc83c3cff)); // 落款 / the seal
108 // 腰板 / wainscot 263 // 腰板 / wainscot
109 b.drawRect({0, 222, 640, 38}, kWainscot); 264 b.drawRect({-8, 222, 656, 38}, kWainscot);
110 b.drawRect({0, 222, 640, 3}, kWainscotDark); 265 b.drawRect({-8, 222, 656, 3}, kWainscotDark);
111 for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark); 266 for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark);
112 // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective) 267 // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective)
113 float y = 260.0f; 268 float y = 260.0f;
114 int row = 0; 269 int row = 0;
115 for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 20.0f}) { 270 // 最後の段は画面の下より先まで / the last row reaches past the bottom
116 b.drawRect({0, y, 640, h}, row % 2 ? kPlankA : kPlankB); 271 for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 28.0f}) {
117 b.drawRect({0, y, 640, 1}, kPlankLine); 272 b.drawRect({-8, y, 656, h}, row % 2 ? kPlankA : kPlankB);
    273 b.drawRect({-8, y, 656, 1}, kPlankLine);
118 float offset = static_cast<float>((row * 97) % 120); 274 float offset = static_cast<float>((row * 97) % 120);
119 for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine); 275 for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine);
120 y += h; 276 y += h;
@@ -124,66 +280,91 @@ void FightScene::drawBackground() {
124   280  
125 void FightScene::draw(float alpha) { 281 void FightScene::draw(float alpha) {
126 SpriteBatch &b = g.batch; 282 SpriteBatch &b = g.batch;
127 b.begin(camera.matrix(), SpriteSort::Layer); 283 Camera2D view = camera;
    284 // 画面の揺れ:重い一撃のヒットストップ中、カメラを2ピクセルずつ揺らす / screen shake: during a heavy hit's
    285 // hit stop the camera jumps by 2 pixels
    286 if (shake > 0) view.centre += Vec2{shake % 2 ? 2.0f : -2.0f, shake % 4 < 2 ? 1.0f : -1.0f};
    287 b.begin(view.matrix(), SpriteSort::Layer);
128 drawBackground(); 288 drawBackground();
129 // 影:地面に。高く跳ぶほど小さく / shadows on the ground, smaller the higher the jump 289 for (int i = 0; i < 2; ++i)
130 for (const Fighter &f : fighters) { 290 fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0);
131 Vec2 p = lerp(f.previous, f.position, alpha); 291 effects.draw(b);
132 float height = std::clamp((kGroundY - p.y) / 100.0f, 0.0f, 1.0f);    
133 float w = std::round(44.0f * (1.0f - 0.4f * height));    
134 float x = std::round(p.x);    
135 Vec4 c = {0.11f, 0.09f, 0.15f, 0.35f};    
136 b.drawRect({x - w * 0.5f + 4.0f, kGroundY - 3.0f, w - 8.0f, 6.0f}, c, 1.0f);    
137 b.drawRect({x - w * 0.5f, kGroundY - 2.0f, 4.0f, 4.0f}, c, 1.0f);    
138 b.drawRect({x + w * 0.5f - 4.0f, kGroundY - 2.0f, 4.0f, 4.0f}, c, 1.0f);    
139 }    
140 fighters[0].draw(b, alpha, 2.0f);    
141 fighters[1].draw(b, alpha, 3.0f);    
142 if (g.showBoxes) drawDebug(alpha); 292 if (g.showBoxes) drawDebug(alpha);
    293 b.end();
    294 // HUDは揺らさない / the HUD does not shake
    295 b.begin(camera.matrix(), SpriteSort::Layer);
    296 drawHud();
    297 b.end();
    298 }
143   299  
144 // 名前(キャンバスの中のピクセル文字) / names (pixel text inside the canvas) 300 void FightScene::drawHud() {
145 TextStyle name = {.color = hexColor(0xfff4d8ff), .layer = 10.0f, .shadow = kOutline}; 301 SpriteBatch &b = g.batch;
146 b.drawRect({0, 0, 640, 22}, {0.11f, 0.09f, 0.15f, 0.55f}, 9.5f); 302 drawHealthBar(b, {16, 10, 272, 10}, static_cast<float>(fighters[0].health), trail[0], false);
147 g.pixel.draw(b, "1P " + fighters[0].name, {12, 4}, name); 303 drawHealthBar(b, {352, 10, 272, 10}, static_cast<float>(fighters[1].health), trail[1], true);
    304 TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline};
    305 g.pixel.draw(b, "1P " + fighters[0].name, {16, 24}, name);
148 TextStyle right = name; 306 TextStyle right = name;
149 right.align = TextAlign::Right; 307 right.align = TextAlign::Right;
150 g.pixel.draw(b, fighters[1].name + " 2P", {628, 4}, right); 308 g.pixel.draw(b, fighters[1].name + " 2P", {624, 24}, right);
151 TextStyle centre = name; 309 TextStyle centre = name;
152 centre.align = TextAlign::Centre; 310 centre.align = TextAlign::Centre;
153 centre.color = hexColor(0xf2c14eff); 311 centre.color = kGold;
154 g.pixel.draw(b, "練習 TRAINING", {320, 4}, centre); 312 g.pixel.draw(b, "練習", {320, 8}, centre);
155 b.end(); 313 // コンボ数(攻撃した側に) / the combo count (on the attacker's side)
    314 for (int i = 0; i < 2; ++i) {
    315 if (comboTime[i] <= 0) continue;
    316 std::string text = std::to_string(comboHits[i]) + " HITS";
    317 TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right,
    318 .layer = 11.0f, .shadow = kOutline};
    319 g.pixel.draw(b, text, {i == 0 ? 16.0f : 624.0f, 44.0f}, s);
    320 }
    321 if (koTime > 0) drawBigText(b, g.pixel, "K.O.", {320, 130}, hexColor(0xe8483cff), 5.0f);
156 } 322 }
157   323  
158 // F1:押し合いの箱、足元、状態の名前と時間 / F1: push boxes, the feet, the state name and its time 324 // F1:食らい判定(青)、攻撃判定(赤)、押し合い(緑)、ソケット(黄)、状態と技の段階
159 void FightScene::drawDebug(float alpha) { 325 // F1: hurt boxes (blue), hit boxes (red), push boxes (green), sockets (yellow), the state and the move's phase
    326 void FightScene::drawDebug(float /*alpha*/) {
    327 // 判定は今のステップの位置で描く(補間しない:当たりを決めたのはこの位置) / boxes at this step's positions (not
    328 // interpolated: these are the positions the hits were decided at)
160 SpriteBatch &b = g.batch; 329 SpriteBatch &b = g.batch;
    330 static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"};
161 for (const Fighter &f : fighters) { 331 for (const Fighter &f : fighters) {
162 Vec2 p = lerp(f.previous, f.position, alpha); 332 for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 8.0f);
163 Rect box = f.pushbox().translated(p - f.position); 333 Rect push = f.pushbox();
164 box = {std::round(box.x), std::round(box.y), box.w, box.h}; 334 b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 8.1f);
165 b.drawRectOutline(box, hexColor(0x50e070ff), 1.0f, 8.0f); 335 const FrameBoxes &fb = (*g.frameData)[f.frame];
166 b.drawRect({std::round(p.x) - 3, std::round(p.y), 7, 1}, hexColor(0xffffffff), 8.0f); 336 // 攻撃判定:持続フレームの間ずっと。当たった後(もう当たらない)は薄く / the attack box for the whole active
167 b.drawRect({std::round(p.x), std::round(p.y) - 3, 1, 7}, hexColor(0xffffffff), 8.0f); 337 // window; fainter once it has hit (it cannot hit again)
168 char label[64]; 338 if (f.phase() == MovePhase::Active && fb.hit)
169 std::snprintf(label, sizeof label, "%s %d\nVX %.0f VY %.0f", stateName(f.state), f.stateTime, 339 b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 8.2f);
170 static_cast<double>(f.velocity.x + 0.0f), static_cast<double>(f.velocity.y + 0.0f)); // +0:-0を0に / +0 turns -0 into 0 340 for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) {
171 // 3×5の小さな文字は影なし、暗い下地の上に / the tiny 3 × 5 font without a shadow, on a dark plate 341 Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing);
    342 b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 8.3f);
    343 }
    344 char label[96];
    345 if (f.state == FighterState::Attack)
    346 std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime,
    347 f.move->total(), kPhase[static_cast<int>(f.phase())]);
    348 else std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health);
    349 // 左の人の札は左へ、右の人の札は右へずらす(近づいても重ならない) / the left fighter's label goes left, the
    350 // right one's right (no overlap at close range)
    351 const Fighter &other = &f == &fighters[0] ? fighters[1] : fighters[0];
    352 bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && &f == &fighters[0]);
172 Vec2 size = g.tiny.measure(label); 353 Vec2 size = g.tiny.measure(label);
173 Vec2 at = {std::round(p.x), std::round(box.y) - 16.0f}; 354 float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f);
174 b.drawRect({std::round(at.x - size.x * 0.5f) - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, 355 Vec2 at = {x0, std::round(push.y) - 16.0f};
175 {0.11f, 0.09f, 0.15f, 0.8f}, 8.5f); 356 b.drawRect({x0 - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, {0.11f, 0.09f, 0.15f, 0.8f}, 8.5f);
176 g.tiny.draw(b, label, at, {.color = hexColor(0xfff4d8ff), .align = TextAlign::Centre, .layer = 9.0f}); 357 g.tiny.draw(b, label, at, {.color = kText, .layer = 9.0f});
177 } 358 }
178 } 359 }
179   360  
180 void FightScene::drawUi(float /*alpha*/) { 361 void FightScene::drawUi(float /*alpha*/) {
181 // 操作の説明(画面の下、1280×720の文字) / the controls (bottom of the screen, 1280 × 720 text)    
182 SpriteBatch &b = g.batch; 362 SpriteBatch &b = g.batch;
183 b.begin(g.screen.matrix()); 363 b.begin(g.screen.matrix());
184 b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); 364 b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f});
185 TextStyle s = {.color = hexColor(0xe8e0d0ff)}; 365 g.ui.draw(b,
186 g.ui.draw(b, "1P: A D 左右・W ジャンプ・S しゃがむ 2P: カーソルキー / arrow keys F1 当たり箱 / boxes Esc 終了 / quit", 366 "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L 後ろでガード / back = guard "
187 {640, 694}, {.color = s.color, .align = TextAlign::Centre}); 367 "F1 当たり箱 Esc 終了",
    368 {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre});
188 b.end(); 369 b.end();
189 } 370 }

ファイル: a/games/fighter/src/fight_scene.hh | b/games/fighter/src/fight_scene.hh

前新
@@ -1,7 +1,8 @@
1 // 対戦の場面:二人のファイター、押し合い、画面の端、道場の背景 1 // 対戦の場面:二人のファイター、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト
2 // The fight scene: two fighters, pushing apart, the stage edges, the dojo background 2 // The fight scene: two fighters, pushing, hits, hit stop, health bars, effects
3 #pragma once 3 #pragma once
4   4  
    5 #include "effects.hh"
5 #include "fighter.hh" 6 #include "fighter.hh"
6 #include "game.hh" 7 #include "game.hh"
7   8  
@@ -16,10 +17,24 @@ public:
16   17  
17 private: 18 private:
18 void separate(); 19 void separate();
    20 void resolveHits();
    21 void resetRound();
19 void drawBackground(); 22 void drawBackground();
    23 void drawHud();
20 void drawDebug(float alpha); 24 void drawDebug(float alpha);
21   25  
22 Game &g; 26 Game &g;
23 Camera2D camera; // 640×360のキャンバス / the 640 × 360 canvas 27 Camera2D camera;
24 Fighter fighters[2]; 28 Fighter fighters[2];
    29 Effects effects;
    30 GamepadEdges pads[2];
    31 int steps = 0;
    32 int hitstop = 0; // 残りのヒットストップ(二人とも止まる) / hit stop left (both fighters frozen)
    33 int victim = -1; // ヒットストップ中に震える方 / who shakes during the hit stop
    34 int shake = 0; // 画面の揺れ / screen shake
    35 int top = 0; // 手前に描くファイター(最後に攻撃した方) / the fighter drawn in front (the last attacker)
    36 float trail[2] = {kMaxHealth, kMaxHealth}; // 体力ゲージの減っていく白い部分 / the health bar's draining trail
    37 int trailDelay[2] = {0, 0};
    38 int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; // 「2 HITS」の表示 / the "2 HITS" display
    39 int koTime = 0; // KOからの時間(練習では仕切り直す) / time since a KO (training resets)
25 }; 40 };

ファイル: a/games/fighter/src/fighter.cc | b/games/fighter/src/fighter.cc

前新
@@ -1,6 +1,8 @@
1 // ファイター:状態機械と2Dの物理 / a fighter: the state machine and 2D physics 1 // ファイター:状態機械、2Dの物理、技、判定、部品のシーングラフ / a fighter: state machine, 2D physics, moves, boxes,
    2 // the parts' scene graph
2 #include "fighter.hh" 3 #include "fighter.hh"
3   4  
    5 #include <algorithm>
4 #include <cmath> 6 #include <cmath>
5   7  
6 namespace { 8 namespace {
@@ -9,22 +11,28 @@ namespace {
9 // steps), speeds in pixels per second 11 // steps), speeds in pixels per second
10 constexpr float kWalkForward = 130.0f; 12 constexpr float kWalkForward = 130.0f;
11 constexpr float kWalkBack = 100.0f; 13 constexpr float kWalkBack = 100.0f;
12 constexpr float kJumpSpeed = 560.0f; // 上向きの初速 / initial upward speed 14 constexpr float kJumpSpeed = 560.0f;
13 constexpr float kJumpForward = 150.0f; // 前後ジャンプの横の速さ / horizontal speed of a forward / back jump 15 constexpr float kJumpForward = 150.0f;
14 constexpr float kGravity = 1800.0f; // 高さ v²/2g ≈ 87 px、滞空 2v/g ≈ 0.62 s(37フレーム) / height v²/2g ≈ 87 px, 16 constexpr float kGravity = 1800.0f;
15 // air time 2v/g ≈ 0.62 s (37 frames) 17 constexpr float kFriction = 1400.0f; // 地上で滑るときの減速(ピクセル毎秒毎秒) / ground deceleration when sliding
16 constexpr int kJumpSquatFrames = 4; 18 constexpr int kJumpSquatFrames = 4;
17 constexpr int kLandFrames = 4; 19 constexpr int kLandFrames = 4;
18 constexpr int kCrouchInFrames = 3; // しゃがみ始めのコマを見せる時間 / how long the "going down" frame shows 20 constexpr int kCrouchInFrames = 3;
    21 constexpr int kLieFrames = 40; // ダウンして寝ている時間 / how long a knocked-down fighter lies
    22 constexpr int kGetUpFrames = 14;
19   23  
20 // コマの原点:128×120のセルの中の足元(64, 116) / the frame origin: the feet at (64, 116) in the 128 × 120 cell    
21 constexpr Vec2 kPivot = {64.0f / 128.0f, 116.0f / 120.0f}; 24 constexpr Vec2 kPivot = {64.0f / 128.0f, 116.0f / 120.0f};
    25 constexpr float kPi = 3.14159265f;
22   26  
23 int findFrame(const SpriteSheet &sheet, const char *name) { 27 int findFrame(const SpriteSheet &sheet, const char *name) {
24 int i = sheet.find(name); 28 int i = sheet.find(name);
25 return i >= 0 ? i : 0; 29 return i >= 0 ? i : 0;
26 } 30 }
27   31  
    32 float approach(float value, float target, float amount) {
    33 return value < target ? std::min(value + amount, target) : std::max(value - amount, target);
    34 }
    35  
28 } // namespace 36 } // namespace
29   37  
30 const char *stateName(FighterState state) { 38 const char *stateName(FighterState state) {
@@ -35,35 +43,134 @@ const char *stateName(FighterState state) {
35 case FighterState::JumpSquat: return "JUMPSQUAT"; 43 case FighterState::JumpSquat: return "JUMPSQUAT";
36 case FighterState::Air: return "AIR"; 44 case FighterState::Air: return "AIR";
37 case FighterState::Land: return "LAND"; 45 case FighterState::Land: return "LAND";
    46 case FighterState::Attack: return "ATTACK";
    47 case FighterState::Hitstun: return "HITSTUN";
    48 case FighterState::Blockstun: return "BLOCKSTUN";
    49 case FighterState::Knockdown: return "KNOCKDOWN";
    50 case FighterState::GetUp: return "GETUP";
    51 case FighterState::KO: return "KO";
38 } 52 }
39 return "?"; 53 return "?";
40 } 54 }
41   55  
42 Fighter::Fighter(const SpriteSheet &s, std::string fighterName, Vec2 start, float startFacing) 56 Fighter::Fighter(const SpriteSheet &s, const SpriteSheet &effects, const FrameData &frameData, std::string fighterName,
43 : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), 57 const char *tail, Vec2 start, float startFacing)
    58 : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData),
44 idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")), 59 idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")),
45 fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), 60 fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")),
46 fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")) { 61 fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")),
    62 fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")),
    63 fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) {
47 animator.play(idleClip); 64 animator.play(idleClip);
48 frame = animator.frame(); 65 frame = animator.frame();
    66 buildParts(effects, tail);
    67 }
    68  
    69 void Fighter::reset(Vec2 start, float startFacing) {
    70 position = previous = start;
    71 velocity = {0.0f, 0.0f};
    72 facing = startFacing;
    73 state = FighterState::Idle;
    74 stateTime = stun = combo = 0;
    75 health = kMaxHealth;
    76 move = nullptr;
    77 onGround = true;
    78 buffer.clear();
    79 animator.play(idleClip, true);
    80 frame = animator.frame();
    81 }
    82  
    83 // 体の部品の木を作る。コマ(body)は一枚の絵、そこに鉢巻の尾(回る部品の鎖)と星(ダウン中)と影を付ける
    84 // Builds the parts tree. The frame (body) is one picture; the headband tails (a chain of rotating parts), the stars
    85 // (while down) and the shadow are attached to it
    86 void Fighter::buildParts(const SpriteSheet &fx, const char *tail) {
    87 root = std::make_unique<Node>("fighter");
    88 shadow = &root->add("shadow");
    89 shadow->sprite = fx.sprite(fx.find("shadow"), {}, {0.5f, 0.5f});
    90 shadow->sprite->color = {1.0f, 1.0f, 1.0f, 0.35f};
    91 shadow->sprite->layer = -1.5f; // どのファイターよりも奥 / behind both fighters
    92 body = &root->add("body");
    93 body->sprite = sheet.sprite(frame, {}, kPivot);
    94 // 頭のソケット → 星の輪(縦につぶす)→ 星(つぶれを打ち消す) / the head socket → the star ring (squashed
    95 // vertically) → stars (canceling the squash)
    96 head = &body->add("head");
    97 stars = &head->add("stars");
    98 stars->position = {0.0f, -13.0f};
    99 stars->scale = {1.0f, 0.35f};
    100 stars->visible = false;
    101 for (Node *&n : starNodes) {
    102 n = &stars->add("star");
    103 n->scale = {1.0f, 1.0f / 0.35f};
    104 n->sprite = fx.sprite(fx.find("star"), {}, {0.5f, 0.5f});
    105 }
    106 // 結び目 → 尾1 → 尾2:子は親の回転を受け継ぐので、尾2のrotationは尾1に対する曲がりだけ
    107 // knot → tail 1 → tail 2: a child inherits its parent's rotation, so tail 2's rotation is only its bend relative
    108 // to tail 1
    109 knot = &body->add("knot");
    110 int t = fx.find(tail);
    111 Vec2 tailOrigin = {1.0f / 12.0f, 0.5f}; // 左の真ん中が付け根 / the root is at the left middle
    112 tail1 = &knot->add("tail1");
    113 tail1->sprite = fx.sprite(t, {}, tailOrigin);
    114 tail1->sprite->layer = -0.2f; // 体の後ろ / behind the body
    115 tail2 = &tail1->add("tail2");
    116 tail2->position = {9.0f, 0.0f};
    117 tail2->scale = {0.85f, 0.85f};
    118 tail2->sprite = tail1->sprite;
49 } 119 }
50   120  
51 // 状態を変える。同じ状態なら時間を数え続ける / changes the state; the same state keeps counting    
52 void Fighter::setState(FighterState next) { 121 void Fighter::setState(FighterState next) {
53 if (next == state) return; 122 if (next == state) return;
54 state = next; 123 state = next;
55 stateTime = 0; 124 stateTime = 0;
56 } 125 }
57   126  
58 void Fighter::update(float dt, const Controls &c, float opponentX) { 127 bool Fighter::actionable() const {
    128 return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch;
    129 }
    130  
    131 // 技を始める。押したステップが発生の1フレーム目 / starts a move; the step of the press is startup frame 1
    132 void Fighter::startMove(MoveId id) {
    133 moveId = id;
    134 move = &moveData(id);
    135 moveHit = false;
    136 state = FighterState::Attack;
    137 stateTime = 1;
    138 if (!move->air) velocity.x = 0.0f;
    139 }
    140  
    141 // バッファにある突き・蹴りを技にする(しゃがみ中は下段の技) / turns a buffered punch or kick into a move (crouching
    142 // moves while crouching)
    143 bool Fighter::tryMoves(bool crouching) {
    144 if (buffer.take(Button::Kick)) {
    145 startMove(crouching ? MoveId::Sweep : MoveId::Kick);
    146 return true;
    147 }
    148 if (buffer.take(Button::Punch)) {
    149 startMove(crouching ? MoveId::CrouchPunch : MoveId::Punch);
    150 return true;
    151 }
    152 return false;
    153 }
    154  
    155 MovePhase Fighter::phase() const {
    156 if (state != FighterState::Attack || !move) return MovePhase::None;
    157 if (stateTime <= move->startup) return MovePhase::Startup;
    158 if (stateTime <= move->startup + move->active) return MovePhase::Active;
    159 return MovePhase::Recovery;
    160 }
    161  
    162 void Fighter::update(float dt, const Controls &c, float opponentX, bool threat) {
    163 controls = c;
    164 landed = false;
    165 guarding = false;
    166 time += dt;
59 ++stateTime; 167 ++stateTime;
60 switch (state) { 168 switch (state) {
61 case FighterState::Idle: 169 case FighterState::Idle:
62 case FighterState::Walk: 170 case FighterState::Walk:
63 case FighterState::Crouch: { 171 case FighterState::Crouch: {
64 // 地上で自由に動ける状態:いつも相手の方を向く(ぴったり重なったら向きを変えない)    
65 // Free on the ground: always face the opponent (keep the facing when exactly on top of each other)    
66 if (std::abs(opponentX - position.x) > 1.0f) facing = opponentX > position.x ? 1.0f : -1.0f; 172 if (std::abs(opponentX - position.x) > 1.0f) facing = opponentX > position.x ? 1.0f : -1.0f;
    173 if (tryMoves(c.down)) break; // 技はほかの動きより先 / moves take priority over movement
67 bool fwd = forward(c, facing), bwd = back(c, facing); 174 bool fwd = forward(c, facing), bwd = back(c, facing);
68 if (c.up) { 175 if (c.up) {
69 jumpDirection = fwd ? 1.0f : bwd ? -1.0f : 0.0f; 176 jumpDirection = fwd ? 1.0f : bwd ? -1.0f : 0.0f;
@@ -71,7 +178,14 @@ void Fighter::update(float dt, const Controls &c, float opponentX) {
71 setState(FighterState::JumpSquat); 178 setState(FighterState::JumpSquat);
72 } else if (c.down) { 179 } else if (c.down) {
73 velocity.x = 0.0f; 180 velocity.x = 0.0f;
    181 guarding = bwd && threat;
74 setState(FighterState::Crouch); 182 setState(FighterState::Crouch);
    183 } else if (bwd && threat) {
    184 // 近接ガード:攻撃が来るときに後ろを押すと、下がらずにその場で構える / proximity guard: holding back while an
    185 // attack is coming guards in place instead of walking away
    186 velocity.x = 0.0f;
    187 guarding = true;
    188 setState(FighterState::Idle);
75 } else if (fwd || bwd) { 189 } else if (fwd || bwd) {
76 walkingBack = bwd; 190 walkingBack = bwd;
77 velocity.x = facing * (fwd ? kWalkForward : -kWalkBack); 191 velocity.x = facing * (fwd ? kWalkForward : -kWalkBack);
@@ -83,74 +197,242 @@ void Fighter::update(float dt, const Controls &c, float opponentX) {
83 break; 197 break;
84 } 198 }
85 case FighterState::JumpSquat: 199 case FighterState::JumpSquat:
86 // 「ため」の間はまだ地面。終わったら跳ぶ:上向きの速度と、決めた向きへの横の速度    
87 // Still on the ground during the squat. Then take off: an upward velocity plus the chosen horizontal one    
88 if (stateTime >= kJumpSquatFrames) { 200 if (stateTime >= kJumpSquatFrames) {
89 velocity = {facing * jumpDirection * kJumpForward, -kJumpSpeed}; 201 velocity = {facing * jumpDirection * kJumpForward, -kJumpSpeed};
    202 onGround = false;
    203 airMoveUsed = false;
90 setState(FighterState::Air); 204 setState(FighterState::Air);
91 } 205 }
92 break; 206 break;
93 case FighterState::Air: 207 case FighterState::Air:
94 velocity.y += kGravity * dt; // 重力:速度を変える(位置は下で速度から) / gravity changes the velocity (the 208 // 空中技は一回のジャンプで一度 / one air move per jump
95 // position follows from the velocity below) 209 if (!airMoveUsed && (buffer.take(Button::Kick) || buffer.take(Button::Punch))) {
    210 airMoveUsed = true;
    211 startMove(MoveId::JumpKick);
    212 }
96 break; 213 break;
97 case FighterState::Land: 214 case FighterState::Land:
98 if (stateTime >= kLandFrames) setState(FighterState::Idle); 215 if (stateTime >= kLandFrames) setState(FighterState::Idle);
99 break; 216 break;
    217 case FighterState::Attack:
    218 // 地上技は全体フレームが終わったら自由に。空中技は着地で終わる(onLanding) / a ground move frees the fighter
    219 // after its total frames; an air move ends on landing (onLanding)
    220 if (!move->air && stateTime > move->total()) {
    221 move = nullptr;
    222 setState(c.down ? FighterState::Crouch : FighterState::Idle);
    223 }
    224 break;
    225 case FighterState::Hitstun:
    226 case FighterState::Blockstun:
    227 if (--stun <= 0) setState(c.down ? FighterState::Crouch : FighterState::Idle);
    228 break;
    229 case FighterState::Knockdown:
    230 if (onGround && --stun <= 0) setState(FighterState::GetUp);
    231 break;
    232 case FighterState::GetUp:
    233 if (stateTime >= kGetUpFrames) setState(FighterState::Idle);
    234 break;
    235 case FighterState::KO:
    236 break;
100 } 237 }
101   238  
102 // 半陰的オイラー法:速度を先に、その速度で位置を / semi-implicit Euler: velocity first, then the position with it 239 // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops
    240 // everything except walking
    241 if (!onGround) velocity.y += kGravity * dt;
    242 else if (state != FighterState::Walk) velocity.x = approach(velocity.x, 0.0f, kFriction * dt);
103 position += velocity * dt; 243 position += velocity * dt;
104   244 if (!onGround && velocity.y > 0.0f && position.y >= kGroundY) {
105 // 地面:落ちてきて地面より下なら、地面に置いて着地 / the ground: when falling below it, put the fighter on it and land    
106 if (state == FighterState::Air && velocity.y > 0.0f && position.y >= kGroundY) {    
107 position.y = kGroundY; 245 position.y = kGroundY;
108 velocity = {0.0f, 0.0f}; 246 velocity.y = 0.0f;
109 setState(FighterState::Land); 247 onGround = true;
    248 onLanding();
110 } 249 }
111 chooseFrame(dt); 250 chooseFrame(dt);
    251 updateParts(dt);
    252 }
    253  
    254 void Fighter::onLanding() {
    255 landed = true;
    256 switch (state) {
    257 case FighterState::Air:
    258 case FighterState::Attack: // 空中技の途中で着地 / landing during an air move
    259 move = nullptr;
    260 velocity.x = 0.0f;
    261 setState(FighterState::Land);
    262 break;
    263 case FighterState::Knockdown:
    264 case FighterState::KO:
    265 velocity.x *= 0.3f;
    266 stun = kLieFrames;
    267 break;
    268 default:
    269 break;
    270 }
    271 }
    272  
    273 bool Fighter::canBlock(AttackHeight height, float attackerX) const {
    274 bool canGuard = actionable() || state == FighterState::Blockstun;
    275 if (!canGuard || !onGround) return false;
    276 bool away = attackerX > position.x ? controls.left : controls.right; // 相手と反対を押す / holding away
    277 if (!away) return false;
    278 if (height == AttackHeight::Low && !controls.down) return false; // 下段はしゃがんで / lows: crouch
    279 if (height == AttackHeight::High && controls.down) return false; // 飛び込みは立って / jump-ins: stand
    280 return true;
    281 }
    282  
    283 HitResult Fighter::takeHit(const MoveData &m, float attackerFacing, bool blocked) {
    284 move = nullptr;
    285 if (blocked) {
    286 stun = m.blockstun;
    287 state = FighterState::Blockstun;
    288 stateTime = 0;
    289 velocity.x = attackerFacing * m.knockback * 0.8f;
    290 return HitResult::Blocked;
    291 }
    292 // のけぞり中・ダウンで飛ばされている間に当たればコンボ / hits during hit stun (or while thrown) add to the combo
    293 combo = state == FighterState::Hitstun || state == FighterState::Knockdown ? combo + 1 : 1;
    294 health = std::max(0, health - m.damage);
    295 if (health == 0) {
    296 state = FighterState::KO;
    297 stateTime = 0;
    298 onGround = false;
    299 velocity = {attackerFacing * 190.0f, -430.0f};
    300 return HitResult::KO;
    301 }
    302 if (m.knockdown || !onGround) {
    303 // 足払い、または空中で当たった:ダウン / a sweep, or hit in the air: knocked down
    304 state = FighterState::Knockdown;
    305 stateTime = 0;
    306 onGround = false;
    307 velocity = {attackerFacing * 140.0f, m.knockdown ? -260.0f : -200.0f};
    308 return HitResult::Hit;
    309 }
    310 stun = m.hitstun;
    311 state = FighterState::Hitstun;
    312 stateTime = 0;
    313 velocity.x = attackerFacing * m.knockback;
    314 return HitResult::Hit;
    315 }
    316  
    317 Rect Fighter::pushbox() const {
    318 bool low = state == FighterState::Crouch || (state == FighterState::Attack && move && move->height == AttackHeight::Low) ||
    319 state == FighterState::KO || state == FighterState::Knockdown || state == FighterState::GetUp ||
    320 ((state == FighterState::Hitstun || state == FighterState::Blockstun) && controls.down);
    321 // 幅は絵の胴と脚くらい(狭すぎると密着したとき体がめり込んで見える) / about as wide as the drawn torso and legs
    322 // (too narrow and the bodies sink into each other at close range)
    323 // 倒れている間は横に長い(体が画面の外にはみ出さない) / long and flat while lying (the body never leaves the screen)
    324 bool lying = onGround && (state == FighterState::Knockdown || state == FighterState::KO);
    325 Rect local = lying ? Rect{-40.0f, -24.0f, 80.0f, 24.0f}
    326 : !onGround ? Rect{-15.0f, -86.0f, 30.0f, 58.0f}
    327 : low ? Rect{-21.0f, -60.0f, 42.0f, 60.0f}
    328 : Rect{-19.0f, -88.0f, 38.0f, 88.0f};
    329 return local.translated(position);
    330 }
    331  
    332 std::vector<Rect> Fighter::hurtboxes() const {
    333 std::vector<Rect> out;
    334 // ダウン中・起き上がり・KOは無敵(追い打ちなし) / invincible while down, getting up or KO'd (no hits on the ground)
    335 if (state == FighterState::Knockdown || state == FighterState::GetUp || state == FighterState::KO) return out;
    336 for (const Rect &r : data[frame].hurt) out.push_back(toWorld(r, position, facing));
    337 return out;
    338 }
    339  
    340 std::optional<Rect> Fighter::activeHitbox() const {
    341 if (phase() != MovePhase::Active || moveHit) return std::nullopt;
    342 const std::optional<Rect> &hit = data[frame].hit;
    343 if (!hit) return std::nullopt;
    344 return toWorld(*hit, position, facing);
112 } 345 }
113   346  
114 // 状態からコマを選ぶ。ループする動き(立ち・歩き)はAnimator、それ以外は状態と速度で決める    
115 // Picks the frame from the state. Looping motions (idle, walk) use the Animator; the rest depend on state and velocity    
116 void Fighter::chooseFrame(float dt) { 347 void Fighter::chooseFrame(float dt) {
    348 bool crouched = controls.down;
117 switch (state) { 349 switch (state) {
118 case FighterState::Idle: 350 case FighterState::Idle:
    351 if (guarding) {
    352 frame = fBlock;
    353 return;
    354 }
119 animator.play(idleClip); 355 animator.play(idleClip);
120 break; 356 break;
121 case FighterState::Walk: 357 case FighterState::Walk:
122 animator.play(walkingBack ? walkBackClip : walkClip); 358 animator.play(walkingBack ? walkBackClip : walkClip);
123 break; 359 break;
124 case FighterState::Crouch: 360 case FighterState::Crouch:
125 frame = stateTime < kCrouchInFrames ? fCrouchIn : fCrouch; 361 frame = guarding ? fCBlock : stateTime < kCrouchInFrames ? fCrouchIn : fCrouch;
126 return; 362 return;
127 case FighterState::JumpSquat: 363 case FighterState::JumpSquat:
128 case FighterState::Land: 364 case FighterState::Land:
    365 case FighterState::GetUp:
129 frame = fCrouchIn; 366 frame = fCrouchIn;
130 return; 367 return;
131 case FighterState::Air: 368 case FighterState::Air:
132 // 上昇中・頂点の近く・落下中 / rising, near the top, falling    
133 frame = velocity.y < -180.0f ? fJumpUp : velocity.y < 180.0f ? fJumpTuck : fJumpDown; 369 frame = velocity.y < -180.0f ? fJumpUp : velocity.y < 180.0f ? fJumpTuck : fJumpDown;
134 return; 370 return;
    371 case FighterState::Attack: {
    372 // 技のコマは時間(フレームデータ)で決まる。アニメーションのfpsではない / a move's frame comes from its timeline
    373 // (the frame data), not from an animation fps
    374 MovePhase p = phase();
    375 const char *frameName = move->frames[p == MovePhase::Startup ? 0 : p == MovePhase::Active ? 1 : 2];
    376 frame = findFrame(sheet, frameName);
    377 return;
    378 }
    379 case FighterState::Hitstun:
    380 frame = crouched ? fCHit : stateTime < 6 ? fHit1 : fHit0; // 最初に大きくのけぞる / the big recoil comes first
    381 return;
    382 case FighterState::Blockstun:
    383 frame = crouched ? fCBlock : fBlock;
    384 return;
    385 case FighterState::Knockdown:
    386 case FighterState::KO:
    387 frame = onGround ? fKo1 : fKo0;
    388 return;
135 } 389 }
136 animator.update(dt); 390 animator.update(dt);
137 frame = animator.frame(); 391 frame = animator.frame();
138 } 392 }
139   393  
140 Rect Fighter::pushbox() const { 394 // 部品の動き(ステップごと):鉢巻の尾はばねで角度を追いかけ、星は頭の周りを回る
141 // 足元からの箱。空中は脚をたたむので下が空く(相手の上を越えられる) / boxes from the feet; in the air the legs are 395 // Part motion (per step): the headband tails chase their angles with springs, the stars circle the head
142 // tucked, so the bottom is open (a fighter can pass over the other) 396 void Fighter::updateParts(float dt) {
143 Rect local = state == FighterState::Crouch ? Rect{-15.0f, -60.0f, 30.0f, 60.0f} 397 // 右向きの空間で考える(左向きはrootの拡大(-1, 1)が鏡に映す)。角度π = 後ろ向き、π − a = 後ろで少し下がる
144 : state == FighterState::Air ? Rect{-13.0f, -86.0f, 26.0f, 58.0f} 398 // Think in facing-right space (root's scale (-1, 1) mirrors it when facing left). Angle π = pointing back,
145 : Rect{-14.0f, -88.0f, 28.0f, 88.0f}; 399 // π − a = back and drooping a little
146 return local.translated(position); 400 float vx = velocity.x * facing, vy = velocity.y;
    401 float droop = 0.5f - std::clamp(vx / 260.0f, -0.3f, 0.4f) + std::clamp(-vy / 700.0f, -0.7f, 0.7f);
    402 float target[2] = {kPi - droop + 0.12f * std::sin(time * 8.0f), 0.0f};
    403 for (int i = 0; i < 2; ++i) {
    404 if (i == 1) target[1] = tailAngle[0] - 0.25f + 0.25f * std::sin(time * 8.0f - 1.3f); // 尾2は尾1を少し遅れて
    405 // tail 2 lags tail 1
    406 tailSpeed[i] += ((target[i] - tailAngle[i]) * 160.0f - tailSpeed[i] * 16.0f) * dt;
    407 tailAngle[i] += tailSpeed[i] * dt;
    408 }
    409 tail1->rotation = tailAngle[0];
    410 tail2->rotation = tailAngle[1] - tailAngle[0]; // 親(尾1)に対する角度 / relative to the parent (tail 1)
    411  
    412 // 星:つぶした輪の上を回る。手前の半分は顔の前、奥の半分は後ろに描く / stars: around the squashed ring; the near
    413 // half in front of the face, the far half behind
    414 bool down = (state == FighterState::Knockdown || state == FighterState::KO) && onGround;
    415 stars->visible = down;
    416 for (int i = 0; i < 3; ++i) {
    417 float a = time * 5.0f + static_cast<float>(i) * 2.0944f;
    418 starNodes[i]->position = {std::cos(a) * 13.0f, std::sin(a) * 13.0f};
    419 starNodes[i]->sprite->layer = std::sin(a) > 0.0f ? 0.3f : -0.3f;
    420 }
147 } 421 }
148   422  
149 void Fighter::draw(SpriteBatch &batch, float alpha, float layer) const { 423 void Fighter::draw(SpriteBatch &batch, float alpha, float layer, int shake) {
150 // 補間した位置を整数に丸める(ピクセルアートは整数の位置に) / the interpolated position, rounded to whole pixels    
151 Vec2 p = lerp(previous, position, alpha); 424 Vec2 p = lerp(previous, position, alpha);
152 Sprite s = sheet.sprite(frame, {std::round(p.x), std::round(p.y)}, kPivot); 425 root->position = {std::round(p.x), kGroundY};
153 s.flipX = facing < 0.0f; // 絵は右向き:左向きは左右反転 / the art faces right; facing left mirrors it 426 root->scale = {facing, 1.0f};
154 s.layer = layer; 427 float shakeX = shake ? static_cast<float>((shake % 2) * 4 - 2) : 0.0f; // ヒットストップ中の震え / hit-stop shake
155 batch.draw(s); 428 body->position = {shakeX, std::round(p.y - kGroundY)};
    429 body->sprite->uv = sheet.uv(frame);
    430 const FrameBoxes &fb = data[frame];
    431 head->position = fb.head;
    432 knot->position = fb.knot;
    433 float height = std::clamp((kGroundY - p.y) / 100.0f, 0.0f, 1.0f);
    434 float s = 1.0f - 0.4f * height;
    435 shadow->scale = {s, s};
    436 shadow->position = {0.0f, -1.0f};
    437 root->draw(batch, {}, layer);
156 } 438 }

ファイル: a/games/fighter/src/fighter.hh | b/games/fighter/src/fighter.hh

前新
@@ -1,19 +1,27 @@
1 // ファイター:状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理(重力・速度・地面)、コマ送りのアニメーション 1 // ファイター:状態機械、2Dの物理、技(フレームデータ)、食らい・攻撃判定、体の部品のシーングラフ
2 // A fighter: a state machine (idle, walk, crouch, jump), 2D physics (gravity, velocity, the ground) and frame 2 // A fighter: the state machine, 2D physics, moves (frame data), hurt / hit boxes, a scene graph of body parts
3 // animation    
4 #pragma once 3 #pragma once
5   4  
6 #include "controls.hh" 5 #include "controls.hh"
    6 #include "frame_data.hh"
    7 #include "input_buffer.hh"
    8 #include "moves.hh"
    9 #include "scene_graph.hh"
7   10  
8 #include "engine/animation.hh" 11 #include "engine/animation.hh"
9 #include "engine/rect.hh" 12 #include "engine/rect.hh"
10 #include "engine/sprite_batch.hh" 13 #include "engine/sprite_batch.hh"
11 #include "engine/sprite_sheet.hh" 14 #include "engine/sprite_sheet.hh"
12   15  
    16 #include <algorithm>
    17 #include <memory>
    18 #include <optional>
13 #include <string> 19 #include <string>
    20 #include <vector>
14   21  
15 // キャンバスは640×360(画面に2倍)。足元のy座標 / the canvas is 640 × 360 (×2 on screen). The y of the feet 22 // キャンバスは640×360(画面に2倍)。足元のy座標 / the canvas is 640 × 360 (×2 on screen). The y of the feet
16 constexpr float kGroundY = 320.0f; 23 constexpr float kGroundY = 320.0f;
    24 constexpr int kMaxHealth = 100;
17   25  
18 // 状態。どの状態でも「何ステップ目か」(stateTime)を数える:格闘ゲームの時間はフレーム数 26 // 状態。どの状態でも「何ステップ目か」(stateTime)を数える:格闘ゲームの時間はフレーム数
19 // The states. Every state counts its steps (stateTime): in fighting games time is measured in frames 27 // The states. Every state counts its steps (stateTime): in fighting games time is measured in frames
@@ -21,47 +29,105 @@ enum class FighterState {
21 Idle, // 立ち / standing 29 Idle, // 立ち / standing
22 Walk, // 歩き(前・後ろ) / walking (forwards or backwards) 30 Walk, // 歩き(前・後ろ) / walking (forwards or backwards)
23 Crouch, // しゃがみ / crouching 31 Crouch, // しゃがみ / crouching
24 JumpSquat, // 跳ぶ前のため(数フレーム、まだ地面) / the crouch before take-off (a few frames, still on the ground) 32 JumpSquat, // 跳ぶ前のため / the crouch before take-off
25 Air, // 空中(放物線、空中では向きも軌道も変えられない) / in the air (a parabola; neither facing nor arc can 33 Air, // 空中 / in the air
26 // change) 34 Land, // 着地の硬さ / landing recovery
27 Land, // 着地の硬さ(数フレーム動けない) / landing recovery (a few frames without control) 35 Attack, // 技を出している(発生 → 持続 → 硬直) / performing a move (startup → active → recovery)
    36 Hitstun, // のけぞり(動けない) / reeling from a hit (no control)
    37 Blockstun, // ガードの硬直 / guarding (no control)
    38 Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up
    39 GetUp, // 起き上がり(無敵) / getting up (invincible)
    40 KO, // 体力0:倒れたまま / health 0: stays down
28 }; 41 };
29 const char *stateName(FighterState state); 42 const char *stateName(FighterState state);
30   43  
    44 enum class HitResult { Hit, Blocked, KO };
    45  
    46 // 技の今の段階 / where a move currently is
    47 enum class MovePhase { None, Startup, Active, Recovery };
    48  
31 class Fighter { 49 class Fighter {
32 public: 50 public:
33 Fighter(const SpriteSheet &sheet, std::string name, Vec2 start, float facing); 51 // sheet:ファイターのコマ、effects:尾・星・影、tail:鉢巻の尾のコマ名 / sheet: the fighter's frames, effects:
    52 // tails, stars, shadow; tail: the headband tail's frame name
    53 Fighter(const SpriteSheet &sheet, const SpriteSheet &effects, const FrameData &data, std::string name,
    54 const char *tail, Vec2 start, float facing);
    55 // 練習の仕切り直し:体力・状態・位置を戻す / a training reset: health, state and position back to the start
    56 void reset(Vec2 start, float startFacing);
34   57  
35 // 1ステップ(1/60秒)進める。opponentXで相手の方を向く / advances one step (1/60 s); faces the opponent at opponentX 58 // 1ステップ(1/60秒)進める。threat = 相手が近くで技を出している(後ろを押すと下がらずに構える)
36 void update(float dt, const Controls &controls, float opponentX); 59 // Advances one step (1/60 s). threat = the opponent is attacking nearby (holding back then guards in place
37 // ステップの最初に呼ぶ:描くときの補間用に今の位置を覚える / call at the start of a step: remembers the position 60 // instead of walking away: "proximity guard")
38 // for interpolation when drawing 61 void update(float dt, const Controls &controls, float opponentX, bool threat);
39 void savePrevious() { previous = position; } 62 void savePrevious() { previous = position; }
40   63  
41 // 押し合いの箱(ワールド座標):二人が重ならないための箱 / the push box (world): keeps the two fighters apart    
42 Rect pushbox() const; 64 Rect pushbox() const;
43 void draw(SpriteBatch &batch, float alpha, float layer) const; 65 // 食らい判定(ワールド)。無敵なら空 / hurt boxes (world); empty while invincible
44 // 前を押しているか(向きに対して) / is "forward" held (relative to the facing) 66 std::vector<Rect> hurtboxes() const;
    67 // 攻撃判定(ワールド):持続フレームで、まだ当たっていないときだけ / the attack box (world): only during active
    68 // frames and before it has hit
    69 std::optional<Rect> activeHitbox() const;
    70 MovePhase phase() const;
    71 // 今の入力でこの技をガードできるか(後ろを押している、高さが合う、ガードできる状態)
    72 // Can the current input block this move (holding back, the right height, a state that can block)
    73 bool canBlock(AttackHeight height, float attackerX) const;
    74 // 当てられた:体力・状態・ノックバック。attackerFacingの向きに押される / got hit: health, state, knockback; pushed
    75 // in attackerFacing's direction
    76 HitResult takeHit(const MoveData &move, float attackerFacing, bool blocked);
    77 void confirmHit() { moveHit = true; } // この技はもう当たった(一回の技で一度だけ) / this move has hit (once per move)
    78 // 壁際で当てたら自分が下がる。同じ向きのもっと速い動き(相打ちで受けたノックバック)は其のまま / pushed back at
    79 // the wall; a faster motion the same way (the knockback just taken in a trade) is kept
    80 void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); }
    81 bool actionable() const;
    82  
    83 // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them
    84 void draw(SpriteBatch &batch, float alpha, float layer, int shake);
45 static bool forward(const Controls &c, float facing) { return facing > 0.0f ? c.right : c.left; } 85 static bool forward(const Controls &c, float facing) { return facing > 0.0f ? c.right : c.left; }
46 static bool back(const Controls &c, float facing) { return facing > 0.0f ? c.left : c.right; } 86 static bool back(const Controls &c, float facing) { return facing > 0.0f ? c.left : c.right; }
47   87  
48 std::string name; 88 std::string name;
49 Vec2 position; // 足元の中心(ワールドのピクセル、y下向き) / the feet center (world pixels, y down) 89 Vec2 position, previous, velocity;
50 Vec2 previous; // 前のステップの位置 / last step's position 90 float facing = 1.0f;
51 Vec2 velocity; // ピクセル毎秒 / pixels per second    
52 float facing = 1.0f; // +1 = 右向き、-1 = 左向き / +1 = facing right, -1 = facing left    
53 FighterState state = FighterState::Idle; 91 FighterState state = FighterState::Idle;
54 int stateTime = 0; // この状態で何ステップ目か / steps spent in this state 92 int stateTime = 0;
    93 int frame = 0;
    94 int health = kMaxHealth;
    95 int stun = 0; // のけぞり・ガード硬直の残り / hit stun / block stun left
    96 int combo = 0; // 連続で食らった数 / hits taken in the current combo
    97 const MoveData *move = nullptr;
    98 MoveId moveId = MoveId::Punch;
    99 bool moveHit = false;
55 bool walkingBack = false; 100 bool walkingBack = false;
56 int frame = 0; // 今のコマ(スプライトシートの番号) / the current frame (sprite-sheet index) 101 bool guarding = false; // 構えている(近くの攻撃に後ろを押している) / holding a guard against a nearby attack
    102 bool landed = false; // このステップで着地した(砂ぼこり用) / landed this step (for dust)
    103 InputBuffer buffer;
    104 Controls controls; // このステップの入力(ガードの判定に) / this step's input (for blocking)
57   105  
58 private: 106 private:
59 void setState(FighterState next); 107 void setState(FighterState next);
    108 void startMove(MoveId id);
    109 bool tryMoves(bool crouching);
    110 void onLanding();
60 void chooseFrame(float dt); 111 void chooseFrame(float dt);
    112 void buildParts(const SpriteSheet &effects, const char *tail);
    113 void updateParts(float dt);
61   114  
62 const SpriteSheet &sheet; 115 const SpriteSheet &sheet;
    116 const FrameData &data;
63 const AnimationClip *idleClip, *walkClip, *walkBackClip; 117 const AnimationClip *idleClip, *walkClip, *walkBackClip;
64 Animator animator; 118 Animator animator;
65 float jumpDirection = 0.0f; // -1 後ろ、0 垂直、+1 前 / -1 back, 0 straight up, +1 forwards 119 float jumpDirection = 0.0f;
66 int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown; 120 bool onGround = true;
    121 bool airMoveUsed = false;
    122 float time = 0.0f;
    123 int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1;
    124  
    125 // シーングラフ:root(足元、向きで左右反転)→ 影、body(コマ)→ 頭のソケット → 星、結び目 → 尾1 → 尾2
    126 // The scene graph: root (the feet, mirrored by facing) → shadow, body (the frame) → head socket → stars,
    127 // knot → tail 1 → tail 2
    128 std::unique_ptr<Node> root;
    129 Node *shadow, *body, *head, *stars, *knot, *tail1, *tail2;
    130 Node *starNodes[3];
    131 float tailAngle[2] = {3.0f, 3.0f}, tailSpeed[2] = {0.0f, 0.0f}; // 尾の世界の角度(右向きの空間で) / the tails'
    132 // angles (in facing-right space)
67 }; 133 };

ファイル: /dev/null | b/games/fighter/src/frame_data.cc

前新
@@ -0,0 +1,60 @@
    1 // コマごとの判定データ / per-frame box data
    2 #include "frame_data.hh"
    3  
    4 #include "engine/file_util.hh"
    5  
    6 #include <cstdio>
    7 #include <sstream>
    8  
    9 std::optional<FrameData> FrameData::load(const std::string &path, const SpriteSheet &sheet) {
    10 std::optional<std::string> text = readTextFile(path);
    11 if (!text) return std::nullopt;
    12 FrameData data;
    13 data.frames.resize(static_cast<size_t>(sheet.count()));
    14 std::istringstream lines(*text);
    15 std::string line;
    16 int number = 0;
    17 while (std::getline(lines, line)) {
    18 ++number;
    19 std::istringstream in(line);
    20 std::string kind, frameName;
    21 if (!(in >> kind) || kind[0] == '#') continue;
    22 in >> frameName;
    23 int index = sheet.find(frameName);
    24 if (index < 0) {
    25 fprintf(stderr, "%s:%d: コマがない / unknown frame '%s'\n", path.c_str(), number, frameName.c_str());
    26 return std::nullopt;
    27 }
    28 FrameBoxes &f = data.frames[static_cast<size_t>(index)];
    29 if (kind == "hurt" || kind == "hit") {
    30 Rect r;
    31 if (!(in >> r.x >> r.y >> r.w >> r.h)) {
    32 fprintf(stderr, "%s:%d: x y w h が要る / expected x y w h\n", path.c_str(), number);
    33 return std::nullopt;
    34 }
    35 if (kind == "hurt") f.hurt.push_back(r);
    36 else f.hit = r;
    37 } else if (kind == "socket") {
    38 std::string name;
    39 Vec2 p;
    40 if (!(in >> name >> p.x >> p.y)) {
    41 fprintf(stderr, "%s:%d: name x y が要る / expected name x y\n", path.c_str(), number);
    42 return std::nullopt;
    43 }
    44 if (name == "head") f.head = p;
    45 else if (name == "knot") f.knot = p;
    46 else if (name == "fist") f.fist = p;
    47 else if (name == "foot") f.foot = p;
    48 } else {
    49 fprintf(stderr, "%s:%d: 知らない行 / unknown line '%s'\n", path.c_str(), number, kind.c_str());
    50 return std::nullopt;
    51 }
    52 }
    53 return data;
    54 }
    55  
    56 Rect toWorld(const Rect &local, Vec2 feet, float facing) {
    57 // 左向きなら左右を反転:x' = -(x + w) / facing left mirrors the box: x' = -(x + w)
    58 float x = facing > 0.0f ? local.x : -(local.x + local.w);
    59 return {feet.x + x, feet.y + local.y, local.w, local.h};
    60 }

ファイル: /dev/null | b/games/fighter/src/frame_data.hh

前新
@@ -0,0 +1,32 @@
    1 // コマごとの判定データ(fighter.boxes):食らい判定、攻撃判定、部品を付ける位置(ソケット)
    2 // Per-frame box data (fighter.boxes): hurt boxes, the attack box, and where parts attach (sockets)
    3 #pragma once
    4  
    5 #include "engine/rect.hh"
    6 #include "engine/sprite_sheet.hh"
    7  
    8 #include <optional>
    9 #include <string>
    10 #include <vector>
    11  
    12 // 足元からの位置、右向き、y下向き(ピクセル) / relative to the feet, facing right, y down (pixels)
    13 struct FrameBoxes {
    14 std::vector<Rect> hurt; // 食らい判定(ここに当たるとやられる) / hurt boxes (getting hit here hurts)
    15 std::optional<Rect> hit; // 攻撃判定(持続フレームのコマだけ) / the attack box (active-frame sprites only)
    16 Vec2 head, knot, fist, foot; // ソケット:頭・鉢巻の結び目・近い拳・近い足 / sockets: head, headband knot, near fist,
    17 // near foot
    18 };
    19  
    20 class FrameData {
    21 public:
    22 // 行の形式 / line format: hurt <frame> x y w h | hit <frame> x y w h | socket <frame> <name> x y | # comment
    23 // コマの名前はsheetで引く(sheetのコマ番号で並ぶ) / frame names are looked up in `sheet` (indexed like the sheet)
    24 static std::optional<FrameData> load(const std::string &path, const SpriteSheet &sheet);
    25 const FrameBoxes &operator[](int frame) const { return frames[static_cast<size_t>(frame)]; }
    26  
    27 private:
    28 std::vector<FrameBoxes> frames;
    29 };
    30  
    31 // 右向きの箱を、向き(±1)と足元の位置でワールドへ / a facing-right box into the world for a facing (±1) and the feet
    32 Rect toWorld(const Rect &local, Vec2 feet, float facing);

ファイル: a/games/fighter/src/game.hh | b/games/fighter/src/game.hh

前新
@@ -2,6 +2,8 @@
2 // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) 2 // The fighting game's shared data, one per game (main creates it, the scenes keep a reference)
3 #pragma once 3 #pragma once
4   4  
    5 #include "frame_data.hh"
    6  
5 #include "engine/camera2d.hh" 7 #include "engine/camera2d.hh"
6 #include "engine/font.hh" 8 #include "engine/font.hh"
7 #include "engine/game_loop.hh" 9 #include "engine/game_loop.hh"
@@ -22,6 +24,8 @@ struct Game {
22 const Font &pixel; // pixel12:キャンバスの中 / inside the canvas 24 const Font &pixel; // pixel12:キャンバスの中 / inside the canvas
23 const Font &tiny; // pixel5:デバッグ表示 / debug labels 25 const Font &tiny; // pixel5:デバッグ表示 / debug labels
24 const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) 26 const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P)
    27 const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow
    28 const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton)
25 Camera2D screen; // 1280×720のUI / the 1280 × 720 UI 29 Camera2D screen; // 1280×720のUI / the 1280 × 720 UI
26 bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels 30 bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels
27 }; 31 };

ファイル: /dev/null | b/games/fighter/src/input_buffer.hh

前新
@@ -0,0 +1,35 @@
    1 // 入力バッファ:ボタンを押してから数フレームの間、その入力を覚えておく。硬直が解けた瞬間に技が出る
    2 // The input buffer: remembers a button press for a few frames, so a move comes out the moment recovery ends
    3 #pragma once
    4  
    5 #include "controls.hh"
    6  
    7 enum class Button { Punch, Kick };
    8  
    9 class InputBuffer {
    10 public:
    11 // 何フレーム前の押下まで有効か(60 Hzで約0.13秒) / how old a press may be (about 0.13 s at 60 Hz)
    12 static constexpr int kWindow = 8;
    13  
    14 // 毎ステップ一回(ヒットストップ中も):押した瞬間を年齢0として記録し、ほかは1つ年を取る
    15 // Once per step (also during hit stop): a fresh press gets age 0, everything else gets one step older
    16 void record(const Controls &c) {
    17 for (int &a : age) a = a < kNone ? a + 1 : kNone;
    18 if (c.punch) age[0] = 0;
    19 if (c.kick) age[1] = 0;
    20 }
    21 // 窓の中に押下があれば使い切ってtrue(一回の押下で技は一つ) / true (and used up) if there is a press inside the
    22 // window: one press, one move
    23 bool take(Button b) {
    24 int &a = age[static_cast<int>(b)];
    25 if (a > kWindow) return false;
    26 a = kNone;
    27 return true;
    28 }
    29 bool waiting(Button b) const { return age[static_cast<int>(b)] <= kWindow; }
    30 void clear() { age[0] = age[1] = kNone; }
    31  
    32 private:
    33 static constexpr int kNone = 1000;
    34 int age[2] = {kNone, kNone};
    35 };

ファイル: a/games/fighter/src/main.cc | b/games/fighter/src/main.cc

前新
@@ -2,12 +2,18 @@
2 // 2 //
3 // 第30章:ファイターの状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理、コマ送りのアニメーション、二人の入力 3 // 第30章:ファイターの状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理、コマ送りのアニメーション、二人の入力
4 // Chapter 30: the fighter state machine (idle, walk, crouch, jump), 2D physics, frame animation, two players' input 4 // Chapter 30: the fighter state machine (idle, walk, crouch, jump), 2D physics, frame animation, two players' input
    5 // 第31章:技(フレームデータ)、攻撃・食らい判定、ダメージ、のけぞり、ノックバック、ヒットストップ、体力ゲージ、
    6 // 入力バッファ、体の部品とエフェクトのシーングラフ
    7 // Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input
    8 // buffering, a scene graph for body parts and effects
5 // 9 //
6 // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): 10 // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard):
7 // 1P A D 前後・W ジャンプ・S しゃがみ / A D walk, W jump, S crouch 11 // 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick
8 // 2P ← → 前後・↑ ジャンプ・↓ しゃがみ / arrow keys 12 // 2P ← → ↑ ↓、K 突き・L 蹴り(テンキーの1・2でも) / arrow keys, K punch, L kick (or keypad 1, 2)
9 // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック) / gamepads: 1st = 1P, 2nd = 2P (d-pad or left stick) 13 // 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching)
10 // F1 押し合いの箱と状態 / push boxes and states Esc 終了 / quit 14 // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P,
    15 // 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick)
    16 // F1 判定の箱と状態 / boxes and states Esc 終了 / quit
11 #include "fight_scene.hh" 17 #include "fight_scene.hh"
12 #include "game.hh" 18 #include "game.hh"
13   19  
@@ -29,7 +35,12 @@ int main() {
29 // frame layout, different colors (a palette swap) 35 // frame layout, different colors (a palette swap)
30 std::optional<SpriteSheet> hayate = SpriteSheet::loadAtlas("games/fighter/assets/hayate.atlas"); 36 std::optional<SpriteSheet> hayate = SpriteSheet::loadAtlas("games/fighter/assets/hayate.atlas");
31 std::optional<SpriteSheet> jin = SpriteSheet::loadAtlas("games/fighter/assets/jin.atlas"); 37 std::optional<SpriteSheet> jin = SpriteSheet::loadAtlas("games/fighter/assets/jin.atlas");
32 if (!batch || !ui || !pixel || !tiny || !hayate || !jin) return 1; 38 std::optional<SpriteSheet> effects = SpriteSheet::loadAtlas("games/fighter/assets/effects.atlas");
    39 if (!batch || !ui || !pixel || !tiny || !hayate || !jin || !effects) return 1;
    40 // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton:
    41 // the same for both (same frame names and indices)
    42 std::optional<FrameData> frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate);
    43 if (!frameData) return 1;
33   44  
34 Input input; 45 Input input;
35 input.attach(window); 46 input.attach(window);
@@ -38,7 +49,7 @@ int main() {
38 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); 49 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
39 PixelCanvas canvas(static_cast<int>(kViewSize.x), static_cast<int>(kViewSize.y)); 50 PixelCanvas canvas(static_cast<int>(kViewSize.x), static_cast<int>(kViewSize.y));
40 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel, 51 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel,
41 .tiny = *tiny, .fighters = {&*hayate, &*jin}, .screen = Camera2D::screen({1280.0f, 720.0f})}; 52 .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .screen = Camera2D::screen({1280.0f, 720.0f})};
42   53  
43 SceneManager scenes; 54 SceneManager scenes;
44 scenes.push(std::make_unique<FightScene>(game)); 55 scenes.push(std::make_unique<FightScene>(game));

ファイル: /dev/null | b/games/fighter/src/moves.cc

前新
@@ -0,0 +1,33 @@
    1 // 技の性能表 / the move table
    2 #include "moves.hh"
    3  
    4 namespace {
    5  
    6 // 有利不利(当てた後どちらが先に動けるか)= 相手の硬直 −(持続の残り + 自分の硬直)。最初の持続フレームで当てた場合:
    7 // 突き:ヒット 17 − (2 + 8) = +7、ガード 10 − 10 = ±0(ヒットなら突き → 突きがつながる:7 ≥ 発生4 + 3)
    8 // 蹴り:ヒット 19 − (3 + 16) = ±0、ガード 13 − 19 = −6(突きの発生4で反撃される)
    9 // 足払い:ダウンを取る、ガード 12 − (2 + 20) = −10(大きな隙)
    10 // つながる条件は 有利 ≥ 発生 + 3:技が終わるステップはIdleに戻るだけ、当たるのは発生の次のフレーム、
    11 // 相手は硬直が0になったステップでもう自由
    12 // Frame advantage (who acts first afterwards) = the opponent's stun − (the rest of the active frames + own recovery).
    13 // Hitting on the first active frame:
    14 // punch: hit 17 − (2 + 8) = +7, block 10 − 10 = ±0 (on hit punch → punch links: 7 ≥ startup 4 + 3)
    15 // kick: hit 19 − (3 + 16) = ±0, block 13 − 19 = −6 (punishable by the 4-frame punch)
    16 // sweep: knocks down; block 12 − (2 + 20) = −10 (a big opening)
    17 // A move links when the advantage ≥ its startup + 3: the step a move ends only returns to Idle, the hit comes on the
    18 // frame after the startup, and the victim is free on the step its stun reaches 0
    19 constexpr MoveData kMoves[] = {
    20 // 名前 / name コマ / frames 発生 持続 硬直 ダメ のけぞり ガード 停止 押し
    21 {"PUNCH", {"punch0", "punch1", "punch2"}, 4, 3, 8, 6, 17, 10, 7, 140.0f, AttackHeight::Mid, false, false},
    22 {"KICK", {"kick0", "kick1", "kick2"}, 8, 4, 16, 12, 19, 13, 11, 230.0f, AttackHeight::Mid, false, false},
    23 {"C.PUNCH", {"cpunch0", "cpunch1", "cpunch2"}, 4, 3, 8, 5, 15, 9, 7, 120.0f, AttackHeight::Mid, false, false},
    24 {"SWEEP", {"sweep0", "sweep1", "sweep2"}, 7, 3, 20, 10, 0, 12, 10, 120.0f, AttackHeight::Low, true, false},
    25 // 飛び蹴り:持続は着地まで(硬直0、着地の硬直は別) / jump kick: active until landing (recovery 0; landing
    26 // recovery comes separately)
    27 {"J.KICK", {"jkick0", "jkick1", "jkick1"}, 6, 40, 0, 10, 18, 12, 10, 160.0f, AttackHeight::High, false, true},
    28 };
    29 static_assert(sizeof(kMoves) / sizeof(kMoves[0]) == static_cast<int>(MoveId::Count));
    30  
    31 } // namespace
    32  
    33 const MoveData &moveData(MoveId id) { return kMoves[static_cast<int>(id)]; }

ファイル: /dev/null | b/games/fighter/src/moves.hh

前新
@@ -0,0 +1,26 @@
    1 // 技の性能表(フレームデータ):発生・持続・硬直、ダメージ、のけぞり、ガード硬直、ヒットストップ、ノックバック
    2 // The move table (frame data): startup, active, recovery, damage, hit stun, block stun, hit stop, knockback
    3 #pragma once
    4  
    5 enum class MoveId { Punch, Kick, CrouchPunch, Sweep, JumpKick, Count };
    6  
    7 // どうガードするか:中段 = 立ちでもしゃがみでも、下段 = しゃがみだけ、上段(飛び込み) = 立ちだけ
    8 // How it must be blocked: mid = standing or crouching, low = crouching only, high (jump-ins) = standing only
    9 enum class AttackHeight { Mid, Low, High };
    10  
    11 struct MoveData {
    12 const char *name;
    13 const char *frames[3]; // コマ:発生・持続・硬直 / sprite frames: startup, active, recovery
    14 int startup, active, recovery; // フレーム数(1/60秒) / frames (1/60 s)
    15 int damage;
    16 int hitstun, blockstun; // 当たった・ガードされた相手が動けないフレーム / frames the opponent cannot act
    17 int hitstop; // 当たった瞬間に二人とも止まるフレーム / frames both freeze on contact
    18 float knockback; // 相手を押す速さ(ピクセル毎秒、摩擦で減る) / push speed (px/s, decays with friction)
    19 AttackHeight height;
    20 bool knockdown; // 当たるとダウン / knocks down on hit
    21 bool air; // 空中技(着地で終わる) / an air move (ends on landing)
    22  
    23 int total() const { return startup + active + recovery; }
    24 };
    25  
    26 const MoveData &moveData(MoveId id);

ファイル: /dev/null | b/games/fighter/src/scene_graph.cc

前新
@@ -0,0 +1,66 @@
    1 // 2Dのシーングラフ / the 2D scene graph
    2 #include "scene_graph.hh"
    3  
    4 #include <algorithm>
    5 #include <cmath>
    6  
    7 Affine2 Affine2::trs(Vec2 position, float rotation, Vec2 scale) {
    8 float c = std::cos(rotation), s = std::sin(rotation);
    9 // 回転行列の列 (c, s) と (-s, c) に、それぞれの拡大を掛ける / the rotation's columns (c, s) and (-s, c), each times
    10 // its scale
    11 return {.x = Vec2{c, s} * scale.x, .y = Vec2{-s, c} * scale.y, .t = position};
    12 }
    13  
    14 Affine2 operator*(const Affine2 &a, const Affine2 &b) {
    15 // bの軸をaの線型部分で変換し、bの原点をaで変換する / b's axes through a's linear part, b's origin through all of a
    16 return {.x = a.x * b.x.x + a.y * b.x.y, .y = a.x * b.y.x + a.y * b.y.y, .t = a.apply(b.t)};
    17 }
    18  
    19 Node &Node::add(std::string childName) { return add(std::make_unique<Node>(std::move(childName))); }
    20  
    21 Node &Node::add(std::unique_ptr<Node> child) {
    22 children.push_back(std::move(child));
    23 return *children.back();
    24 }
    25  
    26 void Node::remove(const Node *child) {
    27 std::erase_if(children, [child](const std::unique_ptr<Node> &c) { return c.get() == child; });
    28 }
    29  
    30 Node *Node::find(std::string_view childName) {
    31 for (auto &c : children) {
    32 if (c->name == childName) return c.get();
    33 if (Node *n = c->find(childName)) return n;
    34 }
    35 return nullptr;
    36 }
    37  
    38 Sprite toSprite(const Sprite &sprite, const Affine2 &world) {
    39 Sprite s = sprite;
    40 float sx = std::hypot(world.x.x, world.x.y), sy = std::hypot(world.y.x, world.y.y);
    41 s.position = world.t;
    42 s.size = {sprite.size.x * sx, sprite.size.y * sy};
    43 if (world.determinant() >= 0.0f) {
    44 s.rotation = std::atan2(world.x.y, world.x.x);
    45 } else {
    46 // 鏡像:world = R(θ)·diag(-sx, sy)。x軸は -(cos θ, sin θ) を向くので θ = atan2(-x.y, -x.x)。
    47 // 絵を左右反転し、基準点も反対側へ(origin.x → 1 - origin.x)
    48 // Mirrored: world = R(θ)·diag(-sx, sy). The x axis points along -(cos θ, sin θ), so θ = atan2(-x.y, -x.x).
    49 // Mirror the picture and move the pivot to the other side (origin.x → 1 - origin.x)
    50 s.rotation = std::atan2(-world.x.y, -world.x.x);
    51 s.flipX = !s.flipX;
    52 s.origin.x = 1.0f - s.origin.x;
    53 }
    54 return s;
    55 }
    56  
    57 void Node::draw(SpriteBatch &batch, const Affine2 &parentWorld, float layerOffset) const {
    58 if (!visible) return;
    59 Affine2 world = parentWorld * local();
    60 if (sprite) {
    61 Sprite s = toSprite(*sprite, world);
    62 s.layer += layerOffset;
    63 batch.draw(s);
    64 }
    65 for (const auto &c : children) c->draw(batch, world, layerOffset);
    66 }

ファイル: /dev/null | b/games/fighter/src/scene_graph.hh

前新
@@ -0,0 +1,72 @@
    1 // 2Dのシーングラフ:親子の変換(位置・回転・拡大)を持つノードの木。キャラクターの部品とエフェクトに使う
    2 // A 2D scene graph: a tree of nodes with parent-child transforms (position, rotation, scale), used for character
    3 // parts and effects
    4 //
    5 // 考え方は第14章のglTFのノードと同じ:world = parent.world × local。違いは2D(2×3の行列)だけ
    6 // The same idea as chapter 14's glTF nodes: world = parent.world × local. Only 2D (a 2 × 3 matrix)
    7 //
    8 // メモ:エンジンに移してもよい(ゲームに依存しない) / note: could move into the engine later (nothing game-specific)
    9 #pragma once
    10  
    11 #include "engine/sprite_batch.hh"
    12  
    13 #include <memory>
    14 #include <optional>
    15 #include <string>
    16 #include <string_view>
    17 #include <vector>
    18  
    19 // 2Dのアフィン変換(2×3):p' = x·p.x + y·p.y + t。xとyは変換後の軸(列)、tは移動
    20 // A 2D affine transform (2 × 3): p' = x·p.x + y·p.y + t. x and y are the transformed axes (columns), t the translation
    21 struct Affine2 {
    22 Vec2 x = {1.0f, 0.0f};
    23 Vec2 y = {0.0f, 1.0f};
    24 Vec2 t = {0.0f, 0.0f};
    25  
    26 // 拡大 → 回転 → 移動(T·R·S)。回転は画面上で時計回り(y下向き、SpriteBatchと同じ)
    27 // scale → rotate → translate (T·R·S). Rotation is clockwise on screen (y down, as in SpriteBatch)
    28 static Affine2 trs(Vec2 position, float rotation, Vec2 scale);
    29 Vec2 apply(Vec2 p) const { return x * p.x + y * p.y + t; }
    30 float determinant() const { return x.x * y.y - x.y * y.x; } // 負 = 鏡に映した / negative = mirrored
    31 };
    32 // a × b:先にb、次にa(親 × 子) / a × b: b first, then a (parent × child)
    33 Affine2 operator*(const Affine2 &a, const Affine2 &b);
    34  
    35 // ノード:ローカルの変換、描くスプライト(なくてもよい)、子供たち。子はunique_ptrなので、ノードへのポインタは
    36 // 親が動いても(vectorが伸びても)変わらない
    37 // A node: a local transform, an optional sprite, children. Children are unique_ptrs, so pointers to nodes stay valid
    38 // when the parent moves (or its vector grows)
    39 class Node {
    40 public:
    41 explicit Node(std::string nodeName = {}) : name(std::move(nodeName)) {}
    42  
    43 // 子を足して、その参照を返す / adds a child and returns a reference to it
    44 Node &add(std::string childName);
    45 Node &add(std::unique_ptr<Node> child);
    46 // 子を外す(なければ何もしない) / removes a child (nothing if it is not one)
    47 void remove(const Node *child);
    48 // 名前で子孫を探す(深さ優先、なければnullptr) / finds a descendant by name (depth first, nullptr if missing)
    49 Node *find(std::string_view childName);
    50  
    51 Affine2 local() const { return Affine2::trs(position, rotation, scale); }
    52 // 木をたどって描く:自分のスプライト、次に子供たち。layerOffsetは全部のスプライトのlayerに足す
    53 // Draws the tree: own sprite first, then the children. layerOffset is added to every sprite's layer
    54 void draw(SpriteBatch &batch, const Affine2 &parentWorld = {}, float layerOffset = 0.0f) const;
    55  
    56 std::string name;
    57 Vec2 position = {0.0f, 0.0f}; // 親の座標系で / in the parent's space
    58 float rotation = 0.0f; // ラジアン、時計回り / radians, clockwise
    59 Vec2 scale = {1.0f, 1.0f}; // (-1, 1) = 左右反転。回転した子の親に縦横違う拡大は不可(せん断になる)
    60 // (-1, 1) = mirrored. No non-uniform scale above a rotated child (that would shear)
    61 bool visible = true; // falseなら子供ごと描かない / false hides the whole subtree
    62 // 描くスプライト:positionは無視(ノードの原点に描く)、originが回転と位置の基準、sizeは拡大前
    63 // The sprite to draw: its position is ignored (drawn at the node's origin), origin is the pivot, size is unscaled
    64 std::optional<Sprite> sprite;
    65 std::vector<std::unique_ptr<Node>> children;
    66 };
    67  
    68 // ワールドの変換をSpriteBatchのSprite(位置・大きさ・回転・左右反転)に直す。鏡に映した変換(行列式 < 0)は
    69 // flipXと、左右を入れ替えたoriginで表す
    70 // Turns a world transform into a SpriteBatch Sprite (position, size, rotation, flipX). A mirrored transform
    71 // (determinant < 0) becomes flipX plus a horizontally swapped origin
    72 Sprite toSprite(const Sprite &sprite, const Affine2 &world);


コメント(0)

まだコメントはありません。