diff --git a/games/fighter/CMakeLists.txt b/games/fighter/CMakeLists.txt index 321c0f5..2141b2a 100644 --- a/games/fighter/CMakeLists.txt +++ b/games/fighter/CMakeLists.txt @@ -3,8 +3,12 @@ add_executable(fighter src/main.cc src/controls.cc + src/effects.cc src/fighter.cc - src/fight_scene.cc) + src/fight_scene.cc + src/frame_data.cc + src/moves.cc + src/scene_graph.cc) target_include_directories(fighter PRIVATE src) target_link_libraries(fighter PRIVATE engine) enable_warnings(fighter) diff --git a/games/fighter/README.md b/games/fighter/README.md index e05ef59..f1f2171 100644 --- 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 | 前後に歩く / walk | A D | ← → | | ジャンプ / jump (+ 前・後ろ / forward, back) | W | ↑ | | しゃがむ / crouch | S | ↓ | +| パンチ / punch | F | K(テンキー / keypad 1) | +| キック / kick | G | L(テンキー / keypad 2) | -ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック)。 -Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick). +* しゃがみ + パンチ = しゃがみパンチ、しゃがみ + キック = 足払い(下段、ダウン)、空中でパンチかキック = 飛び蹴り(上段)。 + Crouch + punch = crouching punch, crouch + kick = sweep (low, knocks down), punch or kick in the air = jump kick (high). +* ガード:相手と反対の方向に入れる。下段はしゃがみガード、飛び蹴りは立ちガードで。 + Guard: hold away from the opponent. Block lows crouching and jump kicks standing. +* 技のボタンは8フレーム覚えておく(入力バッファ)。 / Button presses are remembered for 8 frames (input buffer). -F1 押し合いの箱と状態の表示 / push boxes and states, Esc 終了 / quit. +ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。 +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). + +F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態 / boxes (hurt blue, hit red, push green, +sockets yellow) and states, Esc 終了 / quit. diff --git a/games/fighter/assets/LICENSE.txt b/games/fighter/assets/LICENSE.txt index 4e11703..d1f82b1 100644 --- a/games/fighter/assets/LICENSE.txt +++ b/games/fighter/assets/LICENSE.txt @@ -5,3 +5,7 @@ hayate.png/.atlas 1Pのファイター「ハヤテ」(白い道着、128×12 38 frames of 128 × 120) (chapter 30) jin.png/.atlas 2Pのファイター「ジン」(紺の道着、同じコマ割りの色違い) / player 2's fighter "Jin" (indigo gi, the same frames in other colors) (chapter 30) +fighter.boxes コマごとの食らい判定・攻撃判定・ソケット(骨格から生成) / per-frame hurt boxes, hit boxes and sockets + (made from the skeleton) (chapter 31) +effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars, + shadow (chapter 31) diff --git a/games/fighter/assets/effects.atlas b/games/fighter/assets/effects.atlas new file mode 100644 index 0000000..2b065a9 --- /dev/null +++ b/games/fighter/assets/effects.atlas @@ -0,0 +1,21 @@ +# effects: hit/guard sparks, dust, headband tails, dizzy star, shadow (generated by the author's own script) +image effects.png +sprite spark0 1 1 24 24 +sprite spark1 27 1 24 24 +sprite spark2 53 1 24 24 +sprite spark3 79 1 24 24 +sprite guard0 1 27 24 24 +sprite guard1 27 27 24 24 +sprite guard2 53 27 24 24 +sprite guard3 79 27 24 24 +sprite dust0 105 27 20 12 +sprite dust1 1 53 20 12 +sprite dust2 23 53 20 12 +sprite dust3 45 53 20 12 +sprite tail_hayate 67 53 12 4 +sprite tail_jin 81 53 12 4 +sprite star 95 53 7 7 +sprite shadow 1 67 48 10 +clip spark 30 once spark0 spark1 spark2 spark3 +clip guard 30 once guard0 guard1 guard2 guard3 +clip dust 15 once dust0 dust1 dust2 dust3 diff --git a/games/fighter/assets/effects.png b/games/fighter/assets/effects.png new file mode 100644 index 0000000..20e4e10 Binary files /dev/null and b/games/fighter/assets/effects.png differ diff --git a/games/fighter/assets/fighter.boxes b/games/fighter/assets/fighter.boxes new file mode 100644 index 0000000..f770bc8 --- /dev/null +++ b/games/fighter/assets/fighter.boxes @@ -0,0 +1,283 @@ +# 当たり判定のデータ(作者の自作スクリプトが骨格から作る) / 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 x y w h 食らい判定 / where the fighter can be hit +# hit x y w h 攻撃判定(有効フレームのコマ) / attack box (active frames) +# socket x y 部品・エフェクトの取り付け位置 / where parts and effects attach +hurt idle0 -3 -91 16 16 +hurt idle0 -10 -83 22 46 +hurt idle0 -19 -49 38 50 +socket idle0 head 5 -83 +socket idle0 knot -4 -87 +socket idle0 fist 22 -72 +socket idle0 foot 20 -2 +hurt idle1 -3 -90 16 16 +hurt idle1 -10 -82 22 46 +hurt idle1 -20 -48 39 50 +socket idle1 head 5 -82 +socket idle1 knot -4 -86 +socket idle1 fist 22 -70 +socket idle1 foot 20 -2 +hurt idle2 -3 -89 16 16 +hurt idle2 -10 -81 22 46 +hurt idle2 -20 -47 39 49 +socket idle2 head 5 -81 +socket idle2 knot -4 -85 +socket idle2 fist 22 -69 +socket idle2 foot 20 -2 +hurt idle3 -3 -90 16 16 +hurt idle3 -10 -82 22 46 +hurt idle3 -20 -48 39 50 +socket idle3 head 5 -82 +socket idle3 knot -4 -86 +socket idle3 fist 22 -70 +socket idle3 foot 20 -2 +hurt walk0 -1 -91 16 16 +hurt walk0 -9 -83 23 46 +hurt walk0 -18 -49 41 50 +socket walk0 head 7 -83 +socket walk0 knot -2 -87 +socket walk0 fist 22 -72 +socket walk0 foot 19 -7 +hurt walk1 0 -92 16 16 +hurt walk1 -9 -84 23 46 +hurt walk1 -23 -51 47 52 +socket walk1 head 8 -84 +socket walk1 knot -2 -88 +socket walk1 fist 22 -73 +socket walk1 foot 24 -5 +hurt walk2 0 -92 16 16 +hurt walk2 -9 -84 23 46 +hurt walk2 -24 -51 47 52 +socket walk2 head 8 -84 +socket walk2 knot -2 -88 +socket walk2 fist 22 -73 +socket walk2 foot 24 -3 +hurt walk3 -1 -91 16 16 +hurt walk3 -9 -83 23 46 +hurt walk3 -19 -49 37 51 +socket walk3 head 7 -83 +socket walk3 knot -2 -87 +socket walk3 fist 22 -72 +socket walk3 foot 19 -2 +hurt walk4 -1 -92 16 16 +hurt walk4 -10 -84 23 46 +hurt walk4 -13 -51 28 52 +socket walk4 head 7 -84 +socket walk4 knot -2 -88 +socket walk4 fist 22 -73 +socket walk4 foot 14 -2 +hurt walk5 -1 -92 16 16 +hurt walk5 -10 -84 23 46 +hurt walk5 -13 -51 31 53 +socket walk5 head 7 -84 +socket walk5 knot -2 -88 +socket walk5 fist 22 -73 +socket walk5 foot 14 -5 +hurt crouch_in 0 -80 16 16 +hurt crouch_in -11 -72 25 45 +hurt crouch_in -21 -39 45 41 +socket crouch_in head 8 -72 +socket crouch_in knot -1 -77 +socket crouch_in fist 21 -62 +socket crouch_in foot 22 -2 +hurt crouch 3 -71 16 16 +hurt crouch -12 -63 28 44 +hurt crouch -22 -31 47 32 +socket crouch head 11 -63 +socket crouch knot 2 -68 +socket crouch fist 22 -53 +socket crouch foot 23 -2 +hurt jump_up -2 -93 16 16 +hurt jump_up -9 -85 22 46 +hurt jump_up -13 -51 41 42 +socket jump_up head 6 -85 +socket jump_up knot -3 -89 +socket jump_up fist 19 -81 +socket jump_up foot 14 -19 +hurt jump_tuck 6 -93 16 16 +hurt jump_tuck -9 -85 28 44 +hurt jump_tuck -8 -61 35 36 +socket jump_tuck head 14 -85 +socket jump_tuck knot 5 -90 +socket jump_tuck fist 18 -76 +socket jump_tuck foot 18 -32 +hurt jump_down -4 -94 16 16 +hurt jump_down -9 -85 21 46 +hurt jump_down -15 -51 38 50 +socket jump_down head 4 -86 +socket jump_down knot -5 -89 +socket jump_down fist 21 -78 +socket jump_down foot 14 -7 +hurt punch0 -5 -92 16 16 +hurt punch0 -10 -83 21 46 +hurt punch0 -19 -49 38 50 +socket punch0 head 3 -84 +socket punch0 knot -6 -87 +socket punch0 fist 16 -72 +socket punch0 foot 20 -2 +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 +hurt punch2 1 -91 16 16 +hurt punch2 -8 -83 23 46 +hurt punch2 -19 -49 39 51 +hurt punch2 15 -77 21 21 +socket punch2 head 9 -83 +socket punch2 knot 0 -87 +socket punch2 fist 32 -73 +socket punch2 foot 21 -2 +hurt kick0 -11 -93 16 16 +hurt kick0 -12 -84 18 46 +hurt kick0 -18 -57 42 59 +socket kick0 head -3 -85 +socket kick0 knot -12 -88 +socket kick0 fist 17 -76 +socket kick0 foot 17 -29 +hurt kick1 -20 -93 16 16 +hurt kick1 -18 -85 26 45 +hurt kick1 -18 -52 24 53 +hurt kick1 -3 -66 53 22 +hit kick1 39 -70 18 14 +socket kick1 head -12 -85 +socket kick1 knot -22 -86 +socket kick1 fist 10 -82 +socket kick1 foot 50 -64 +hurt kick2 -14 -93 16 16 +hurt kick2 -14 -84 19 46 +hurt kick2 -18 -50 21 51 +hurt kick2 -6 -56 31 32 +socket kick2 head -6 -85 +socket kick2 knot -15 -87 +socket kick2 fist 17 -78 +socket kick2 foot 25 -28 +hurt sweep0 3 -69 16 16 +hurt sweep0 -13 -61 29 44 +hurt sweep0 -23 -30 49 32 +socket sweep0 head 11 -61 +socket sweep0 knot 2 -65 +socket sweep0 fist 21 -48 +socket sweep0 foot 27 -2 +hurt sweep1 12 -57 16 16 +hurt sweep1 -10 -50 33 41 +hurt sweep1 -21 -21 31 29 +hurt sweep1 -5 -21 54 19 +hit sweep1 37 -11 20 10 +socket sweep1 head 20 -49 +socket sweep1 knot 12 -55 +socket sweep1 fist 30 -9 +socket sweep1 foot 49 -6 +hurt sweep2 6 -65 16 16 +hurt sweep2 -12 -58 31 43 +hurt sweep2 -22 -27 31 29 +hurt sweep2 -7 -28 41 29 +socket sweep2 head 14 -57 +socket sweep2 knot 6 -63 +socket sweep2 fist 26 -42 +socket sweep2 foot 35 -2 +hurt jkick0 4 -94 16 16 +hurt jkick0 -9 -86 27 45 +hurt jkick0 -8 -64 33 37 +socket jkick0 head 12 -86 +socket jkick0 knot 4 -90 +socket jkick0 fist 15 -78 +socket jkick0 foot 20 -34 +hurt jkick1 -14 -97 16 16 +hurt jkick1 -14 -88 20 46 +hurt jkick1 -10 -54 31 25 +hurt jkick1 -5 -54 46 36 +hit jkick1 29 -30 18 14 +socket jkick1 head -6 -89 +socket jkick1 knot -16 -91 +socket jkick1 fist 12 -82 +socket jkick1 foot 40 -25 +hurt cpunch0 1 -72 16 16 +hurt cpunch0 -12 -64 27 45 +hurt cpunch0 -22 -31 47 32 +socket cpunch0 head 9 -64 +socket cpunch0 knot 1 -68 +socket cpunch0 fist 17 -52 +socket cpunch0 foot 23 -2 +hurt cpunch1 8 -70 16 16 +hurt cpunch1 -9 -62 30 43 +hurt cpunch1 -21 -31 49 32 +hurt cpunch1 22 -54 27 9 +hit cpunch1 37 -55 14 10 +socket cpunch1 head 16 -62 +socket cpunch1 knot 8 -67 +socket cpunch1 fist 44 -50 +socket cpunch1 foot 24 -2 +hurt cpunch2 4 -71 16 16 +hurt cpunch2 -11 -63 28 44 +hurt cpunch2 -22 -31 48 33 +hurt cpunch2 15 -56 21 21 +socket cpunch2 head 12 -63 +socket cpunch2 knot 4 -68 +socket cpunch2 fist 32 -52 +socket cpunch2 foot 23 -2 +hurt block -16 -92 16 16 +hurt block -16 -83 19 46 +hurt block -20 -49 37 50 +socket block head -8 -84 +socket block knot -17 -87 +socket block fist 13 -86 +socket block foot 18 -2 +hurt cblock -4 -73 16 16 +hurt cblock -13 -65 24 46 +hurt cblock -22 -31 46 32 +socket cblock head 4 -65 +socket cblock knot -4 -70 +socket cblock fist 14 -63 +socket cblock foot 22 -2 +hurt hit0 -25 -90 16 16 +hurt hit0 -23 -82 25 45 +hurt hit0 -19 -49 37 50 +socket hit0 head -17 -82 +socket hit0 knot -26 -81 +socket hit0 fist 10 -65 +socket hit0 foot 19 -2 +hurt hit1 -33 -87 16 16 +hurt hit1 -30 -79 30 43 +hurt hit1 -19 -48 38 50 +socket hit1 head -25 -79 +socket hit1 knot -34 -76 +socket hit1 fist 4 -61 +socket hit1 foot 20 -3 +hurt chit -12 -75 16 16 +hurt chit -15 -66 19 46 +hurt chit -21 -32 43 34 +socket chit head -4 -67 +socket chit knot -14 -67 +socket chit fist 8 -47 +socket chit foot 22 -2 +hurt ko0 -40 -68 16 16 +hurt ko0 -33 -65 43 31 +hurt ko0 -4 -69 36 34 +socket ko0 head -32 -60 +socket ko0 knot -40 -54 +socket ko0 fist -28 -73 +socket ko0 foot 31 -57 +hurt ko1 -38 -15 87 14 +socket ko1 head -33 -8 +socket ko1 knot -36 1 +socket ko1 fist -46 -1 +socket ko1 foot 45 -11 +hurt win0 -9 -93 16 16 +hurt win0 -9 -84 16 46 +hurt win0 -16 -50 33 51 +socket win0 head -1 -85 +socket win0 knot -11 -86 +socket win0 fist 20 -98 +socket win0 foot 18 -2 +hurt win1 -10 -94 16 16 +hurt win1 -11 -85 18 46 +hurt win1 -16 -51 33 52 +socket win1 head -2 -86 +socket win1 knot -12 -86 +socket win1 fist 19 -98 +socket win1 foot 18 -2 diff --git a/games/fighter/src/controls.cc b/games/fighter/src/controls.cc index 3dbf32a..c305e5b 100644 --- a/games/fighter/src/controls.cc +++ b/games/fighter/src/controls.cc @@ -5,25 +5,38 @@ namespace { // 行動の名前(プレイヤーごと) / action names per player struct ActionNames { - const char *left, *right, *up, *down; + const char *left, *right, *up, *down, *punch, *kick; }; constexpr ActionNames kActions[2] = { - {"p1.left", "p1.right", "p1.up", "p1.down"}, - {"p2.left", "p2.right", "p2.up", "p2.down"}, + {"p1.left", "p1.right", "p1.up", "p1.down", "p1.punch", "p1.kick"}, + {"p2.left", "p2.right", "p2.up", "p2.down", "p2.punch", "p2.kick"}, }; -// ゲームパッド(GLFW 3.3以上のSDL互換マッピング):十字キーか左スティック。つながっていなければ何もしない -// A gamepad (GLFW 3.3+'s SDL-style mapping): the d-pad or the left stick. Does nothing when none is connected -void addGamepad(int player, Controls &c) { +// ゲームパッド(GLFW 3.3以上のSDL互換マッピング):十字キーか左スティック、A/Xで突き、B/Yで蹴り。 +// つながっていなければ何もしない +// 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 +// connected +void addGamepad(int player, Controls &c, GamepadEdges &edges) { int jid = GLFW_JOYSTICK_1 + player; GLFWgamepadstate pad; - if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) return; + if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) { + edges = {}; + return; + } + auto down = [&](int b) { return pad.buttons[b] == GLFW_PRESS; }; constexpr float kDeadZone = 0.5f; float x = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_X], y = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]; - c.left |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT] == GLFW_PRESS || x < -kDeadZone; - c.right |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT] == GLFW_PRESS || x > kDeadZone; - c.up |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP] == GLFW_PRESS || y < -kDeadZone; - c.down |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN] == GLFW_PRESS || y > kDeadZone; + c.left |= down(GLFW_GAMEPAD_BUTTON_DPAD_LEFT) || x < -kDeadZone; + c.right |= down(GLFW_GAMEPAD_BUTTON_DPAD_RIGHT) || x > kDeadZone; + c.up |= down(GLFW_GAMEPAD_BUTTON_DPAD_UP) || y < -kDeadZone; + c.down |= down(GLFW_GAMEPAD_BUTTON_DPAD_DOWN) || y > kDeadZone; + // 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}; } } // namespace @@ -36,17 +49,23 @@ void bindPlayerActions(Input &input) { input.bind(a.right, {InputBinding::key(k.right)}); input.bind(a.up, {InputBinding::key(k.up)}); input.bind(a.down, {InputBinding::key(k.down)}); + input.bind(a.punch, {InputBinding::key(k.punch)}); + input.bind(a.kick, {InputBinding::key(k.kick)}); + if (k.punchAlt >= 0) input.bind(a.punch, {InputBinding::key(k.punchAlt)}); + if (k.kickAlt >= 0) input.bind(a.kick, {InputBinding::key(k.kickAlt)}); } } -Controls readControls(const Input &input, int player) { +Controls readControls(const Input &input, int player, GamepadEdges &pad) { const ActionNames &a = kActions[player]; Controls c; c.left = input.actionHeld(a.left); c.right = input.actionHeld(a.right); c.up = input.actionHeld(a.up); c.down = input.actionHeld(a.down); - addGamepad(player, c); + c.punch = input.actionPressed(a.punch); + c.kick = input.actionPressed(a.kick); + addGamepad(player, c, pad); // 左右同時は「どちらでもない」(格闘ゲームの決まり:SOCD) / left + right together = neither (the fighting-game // rule for simultaneous opposite directions, "SOCD") if (c.left && c.right) c.left = c.right = false; diff --git a/games/fighter/src/controls.hh b/games/fighter/src/controls.hh index 2ea42ad..e1c33d5 100644 --- a/games/fighter/src/controls.hh +++ b/games/fighter/src/controls.hh @@ -4,27 +4,34 @@ #include "engine/input.hh" -// 1ステップ分の入力。方向は押している間、ファイターはこれだけを見る(キーもパッドも知らない) -// One step of input. Directions are "held". The fighter only sees this (it knows nothing about keys or pads) +// 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; }; -// 一人分のキー(GLFW_KEY_…) / one player's keys (GLFW_KEY_...) +// 一人分のキー(GLFW_KEY_…、-1 = なし) / one player's keys (GLFW_KEY_..., -1 = none) struct PlayerKeys { - int left, right, up, down; + int left, right, up, down, punch, kick, punchAlt, kickAlt; }; -// 1P:WASD、2P:矢印キー / 1P: WASD, 2P: the arrow keys +// 1P:WASD + F G、2P:矢印キー + K L(テンキーの1 2でも) / 1P: WASD + F G, 2P: arrow keys + K L (or keypad 1 2) constexpr PlayerKeys kPlayerKeys[2] = { - {GLFW_KEY_A, GLFW_KEY_D, GLFW_KEY_W, GLFW_KEY_S}, - {GLFW_KEY_LEFT, GLFW_KEY_RIGHT, GLFW_KEY_UP, GLFW_KEY_DOWN}, + {GLFW_KEY_A, GLFW_KEY_D, GLFW_KEY_W, GLFW_KEY_S, GLFW_KEY_F, GLFW_KEY_G, -1, -1}, + {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}, }; -// 二人分の行動をInputに登録する("p1.left"、"p2.up"…) / registers both players' actions with Input ("p1.left", -// "p2.up"...) +// ゲームパッドのボタンの前のステップの状態(押した瞬間を作るため) / the gamepad buttons' state in the last step +// (to detect presses) +struct GamepadEdges { + bool punch = false, kick = false; +}; + +// 二人分の行動をInputに登録する("p1.left"、"p2.punch"…) / registers both players' actions with Input ("p1.left", +// "p2.punch"...) void bindPlayerActions(Input &input); // キーボードの行動と、ゲームパッド(GLFW_JOYSTICK_1 + player)を合わせて読む。playerは0か1 // Reads the keyboard actions together with the gamepad (GLFW_JOYSTICK_1 + player). player is 0 or 1 -Controls readControls(const Input &input, int player); +Controls readControls(const Input &input, int player, GamepadEdges &pad); diff --git a/games/fighter/src/effects.cc b/games/fighter/src/effects.cc new file mode 100644 index 0000000..d2e8384 --- /dev/null +++ b/games/fighter/src/effects.cc @@ -0,0 +1,49 @@ +// エフェクト / effects +#include "effects.hh" + +#include + +Effects::Effects(const SpriteSheet &s) + : sheet(s), sparkClip(s.clip("spark")), guardClip(s.clip("guard")), dustClip(s.clip("dust")) {} + +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::spark(Vec2 at, bool guard, bool heavy) { + // 火花は少し回して毎回違って見せる(加算ではなく普通の半透明:ピクセルアートの色のまま) + // Sparks are turned a little so they differ each time (ordinary alpha, not additive: the pixel-art colors stay) + float s = heavy ? 2.0f : 1.0f; + spawn(guard ? guardClip : sparkClip, at, rng.range(0.0f, 1.57f), {s, s}, {0.0f, 0.0f}, 6.0f); +} + +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(); }); +} + +void Effects::clear() { + root.children.clear(); + live.clear(); +} diff --git a/games/fighter/src/effects.hh b/games/fighter/src/effects.hh new file mode 100644 index 0000000..7deca40 --- /dev/null +++ b/games/fighter/src/effects.hh @@ -0,0 +1,37 @@ +// エフェクト:ヒットの火花、ガードの火花、砂ぼこり。どれもシーングラフのノード(effectsの根の子) +// Effects: hit sparks, guard sparks, dust. Each is a scene-graph node (a child of the effects root) +#pragma once + +#include "scene_graph.hh" + +#include "engine/animation.hh" +#include "engine/rng.hh" +#include "engine/sprite_sheet.hh" + +#include + +class Effects { +public: + explicit Effects(const SpriteSheet &sheet); + // 当たった場所に火花。heavyなら大きく / a spark where the hit landed; bigger when heavy + void spark(Vec2 at, bool guard, bool heavy); + // 足元に砂ぼこり(facingの後ろへ流れる) / dust at the feet (drifting behind `facing`) + void dust(Vec2 at, float facing); + void update(float dt); + void draw(SpriteBatch &batch) const { root.draw(batch); } + void clear(); + +private: + struct Live { + Node *node; + Animator animator; + Vec2 velocity; + }; + void spawn(const AnimationClip *clip, Vec2 at, float rotation, Vec2 scale, Vec2 velocity, float layer); + + const SpriteSheet &sheet; + const AnimationClip *sparkClip, *guardClip, *dustClip; + Node root{"effects"}; + std::vector live; + Rng rng{31}; // 火花の向き(固定の種:毎回同じ) / spark angles (fixed seed: identical every run) +}; diff --git a/games/fighter/src/fight_scene.cc b/games/fighter/src/fight_scene.cc index 8f068d3..461d012 100644 --- a/games/fighter/src/fight_scene.cc +++ b/games/fighter/src/fight_scene.cc @@ -1,4 +1,5 @@ -// 対戦の場面(第30章:二人が動き回る練習モード) / the fight scene (chapter 30: a training mode where both move) +// 対戦の場面(第31章:技の当たり、ヒットストップ、体力、エフェクト。KOすると練習を仕切り直す) +// The fight scene (chapter 31: hits, hit stop, health, effects; a KO restarts the training) #include "fight_scene.hh" #include "engine/collision.hh" @@ -7,20 +8,21 @@ #include #include #include +#include namespace { -// 画面の端(押し合いの箱がこの外に出ない) / the stage edges (push boxes never leave them) constexpr float kStageLeft = 16.0f; constexpr float kStageRight = 624.0f; +constexpr Vec2 kStart[2] = {{200.0f, kGroundY}, {440.0f, kGroundY}}; -// 道場の色 / the dojo's colors constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff); constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff); constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff); constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff); constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff); constexpr Vec4 kOutline = hexColor(0x1b1726ff); +constexpr Vec4 kText = hexColor(0xfff4d8ff), kGold = hexColor(0xf2c14eff); void clampToStage(Fighter &f) { Rect b = f.pushbox(); @@ -28,34 +30,119 @@ void clampToStage(Fighter &f) { if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight; } +bool atWall(const Fighter &f) { + Rect b = f.pushbox(); + return b.left() <= kStageLeft + 0.5f || b.right() >= kStageRight - 0.5f; +} + +// 二つの箱の重なり(火花を出す場所) / the overlap of two boxes (where the spark goes) +Rect intersection(const Rect &a, const Rect &b) { + float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top()); + float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom()); + return {l, t, r - l, bt - t}; +} + +// 大きな文字(K.O.など):8方向に輪郭を描いてから本体 / big text (K.O. and so on): an outline in 8 directions, then +// the text itself +void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale) { + Vec2 size = font.measure(text, scale); + Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)}; + TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = 11.0f}; + 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}, + Vec2{3, 4}, Vec2{0, 4}}) + font.draw(b, text, at + d, s); + s.color = color; + s.layer = 11.5f; + font.draw(b, text, at, s); +} + +// 体力ゲージ:中央側に寄せて、外側から減る。白い「跡」は少し遅れて追いかける +// A health bar: anchored at the center side, it drains from the outer end. The white "trail" follows a little later +void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) { + b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f); + b.drawRect(r, hexColor(0x4a2434ff), 10.1f); + auto part = [&](float amount) { + float w = std::round(r.w * std::clamp(amount / static_cast(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); + b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f); + b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f); +} + } // namespace FightScene::FightScene(Game &game) : g(game), camera(Camera2D::screen(kViewSize)), - fighters{Fighter(*game.fighters[0], "HAYATE", {200.0f, kGroundY}, 1.0f), - Fighter(*game.fighters[1], "JIN", {440.0f, kGroundY}, -1.0f)} {} + fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f), + Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)}, + effects(*game.effects) {} + +void FightScene::resetRound() { + fighters[0].reset(kStart[0], 1.0f); + fighters[1].reset(kStart[1], -1.0f); + effects.clear(); + for (int i = 0; i < 2; ++i) { + trail[i] = kMaxHealth; + comboTime[i] = 0; + } + hitstop = shake = koTime = 0; + victim = -1; +} void FightScene::update(float dt) { + ++steps; Input &in = g.input; if (in.pressed(GLFW_KEY_ESCAPE)) { - scenes().pop(); // 最後のシーン:終了 / the last scene: quit + scenes().pop(); return; } if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; - // 二人の入力を先に全部読み、相手の位置もステップの最初の値を使う:1Pを先に動かしても2Pが得をしない - // Read both inputs first and use the opponents' positions from the start of the step: updating 1P first gives - // neither player an advantage - Controls controls[2] = {readControls(in, 0), readControls(in, 1)}; + 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}; - for (Fighter &f : fighters) f.savePrevious(); - for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i]); + 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(fighters[i].health), trail[i] - 0.6f); + } + // 練習:KOから3秒で仕切り直し / training: restart 3 s after a KO + if (koTime > 0 && ++koTime > 180) resetRound(); } -// 押し合い:箱が重なったら半分ずつ離す。片方が壁で止まったら、もう片方がその分も下がる -// Pushing: overlapping push boxes are moved apart by half the overlap each. If one is stopped by a wall, the other -// takes the rest void FightScene::separate() { Fighter &a = fighters[0], &b = fighters[1]; clampToStage(a); @@ -63,26 +150,94 @@ void FightScene::separate() { Rect ra = a.pushbox(), rb = b.pushbox(); if (!overlaps(ra, rb)) return; float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left()); - float dir = a.position.x < b.position.x ? -1.0f : a.position.x > b.position.x ? 1.0f : -a.facing; // aの動く向き / - // a's direction + float dir = a.position.x < b.position.x ? -1.0f : a.position.x > b.position.x ? 1.0f : -a.facing; a.position.x += dir * overlap * 0.5f; b.position.x -= dir * overlap * 0.5f; float ax = a.position.x, bx = b.position.x; clampToStage(a); clampToStage(b); - // 壁が押し返した分を先に両方覚えてから、相手に渡す / remember both wall corrections first, then pass each one on float da = a.position.x - ax, db = b.position.x - bx; b.position.x += da; a.position.x += db; } +// 当たり判定:攻撃側の攻撃判定(持続フレーム)と相手の食らい判定が重なったら当たり。 +// 先に二人分を調べてから当てる:同時に当たったら相打ち +// Hit detection: the attacker's hit box (active frames) overlapping one of the opponent's hurt boxes is a hit. +// Both directions are checked first and applied afterwards: simultaneous hits trade +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 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; + } + } + 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(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]); +} + void FightScene::drawBackground() { SpriteBatch &b = g.batch; + // 画面より8ピクセルずつ広く描く:画面が揺れても端に隙間ができない / drawn 8 pixels wider than the view on every side, + // so the screen shake never opens a gap at the edges // 梁と漆喰の壁 / beams and the plaster wall - b.drawRect({0, 0, 640, 360}, kPlaster); - b.drawRect({0, 0, 640, 34}, kBeam); - b.drawRect({0, 34, 640, 3}, kBeamLight); - b.drawRect({0, 37, 640, 4}, kPlasterShade); + b.drawRect({-8, -8, 656, 376}, kPlaster); + b.drawRect({-8, -8, 656, 42}, kBeam); + b.drawRect({-8, 34, 656, 3}, kBeamLight); + b.drawRect({-8, 37, 656, 4}, kPlasterShade); for (float x = 0; x < 640; x += 160) { b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars b.drawRect({x + 9, 37, 3, 200}, kBeamLight); @@ -106,15 +261,16 @@ void FightScene::drawBackground() { g.pixel.draw(b, "習", {244, 122}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); b.drawRect({236, 166, 16, 8}, hexColor(0xc83c3cff)); // 落款 / the seal // 腰板 / wainscot - b.drawRect({0, 222, 640, 38}, kWainscot); - b.drawRect({0, 222, 640, 3}, kWainscotDark); + b.drawRect({-8, 222, 656, 38}, kWainscot); + b.drawRect({-8, 222, 656, 3}, kWainscotDark); for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark); // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective) float y = 260.0f; int row = 0; - for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 20.0f}) { - b.drawRect({0, y, 640, h}, row % 2 ? kPlankA : kPlankB); - b.drawRect({0, y, 640, 1}, kPlankLine); + // 最後の段は画面の下より先まで / the last row reaches past the bottom + for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 28.0f}) { + b.drawRect({-8, y, 656, h}, row % 2 ? kPlankA : kPlankB); + b.drawRect({-8, y, 656, 1}, kPlankLine); float offset = static_cast((row * 97) % 120); for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine); y += h; @@ -124,66 +280,91 @@ void FightScene::drawBackground() { void FightScene::draw(float alpha) { SpriteBatch &b = g.batch; - b.begin(camera.matrix(), SpriteSort::Layer); + 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(); - // 影:地面に。高く跳ぶほど小さく / shadows on the ground, smaller the higher the jump - for (const Fighter &f : fighters) { - Vec2 p = lerp(f.previous, f.position, alpha); - float height = std::clamp((kGroundY - p.y) / 100.0f, 0.0f, 1.0f); - float w = std::round(44.0f * (1.0f - 0.4f * height)); - float x = std::round(p.x); - Vec4 c = {0.11f, 0.09f, 0.15f, 0.35f}; - b.drawRect({x - w * 0.5f + 4.0f, kGroundY - 3.0f, w - 8.0f, 6.0f}, c, 1.0f); - b.drawRect({x - w * 0.5f, kGroundY - 2.0f, 4.0f, 4.0f}, c, 1.0f); - b.drawRect({x + w * 0.5f - 4.0f, kGroundY - 2.0f, 4.0f, 4.0f}, c, 1.0f); - } - fighters[0].draw(b, alpha, 2.0f); - fighters[1].draw(b, alpha, 3.0f); + 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(); +} - // 名前(キャンバスの中のピクセル文字) / names (pixel text inside the canvas) - TextStyle name = {.color = hexColor(0xfff4d8ff), .layer = 10.0f, .shadow = kOutline}; - b.drawRect({0, 0, 640, 22}, {0.11f, 0.09f, 0.15f, 0.55f}, 9.5f); - g.pixel.draw(b, "1P " + fighters[0].name, {12, 4}, name); +void FightScene::drawHud() { + SpriteBatch &b = g.batch; + drawHealthBar(b, {16, 10, 272, 10}, static_cast(fighters[0].health), trail[0], false); + drawHealthBar(b, {352, 10, 272, 10}, static_cast(fighters[1].health), trail[1], true); + TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline}; + g.pixel.draw(b, "1P " + fighters[0].name, {16, 24}, name); TextStyle right = name; right.align = TextAlign::Right; - g.pixel.draw(b, fighters[1].name + " 2P", {628, 4}, right); + g.pixel.draw(b, fighters[1].name + " 2P", {624, 24}, right); TextStyle centre = name; centre.align = TextAlign::Centre; - centre.color = hexColor(0xf2c14eff); - g.pixel.draw(b, "練習 TRAINING", {320, 4}, centre); - b.end(); + centre.color = kGold; + g.pixel.draw(b, "練習", {320, 8}, centre); + // コンボ数(攻撃した側に) / the combo count (on the attacker's side) + for (int i = 0; i < 2; ++i) { + if (comboTime[i] <= 0) continue; + std::string text = std::to_string(comboHits[i]) + " HITS"; + TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right, + .layer = 11.0f, .shadow = kOutline}; + g.pixel.draw(b, text, {i == 0 ? 16.0f : 624.0f, 44.0f}, s); + } + if (koTime > 0) drawBigText(b, g.pixel, "K.O.", {320, 130}, hexColor(0xe8483cff), 5.0f); } -// F1:押し合いの箱、足元、状態の名前と時間 / F1: push boxes, the feet, the state name and its time -void FightScene::drawDebug(float alpha) { +// F1:食らい判定(青)、攻撃判定(赤)、押し合い(緑)、ソケット(黄)、状態と技の段階 +// F1: hurt boxes (blue), hit boxes (red), push boxes (green), sockets (yellow), the state and the move's phase +void FightScene::drawDebug(float /*alpha*/) { + // 判定は今のステップの位置で描く(補間しない:当たりを決めたのはこの位置) / boxes at this step's positions (not + // interpolated: these are the positions the hits were decided at) SpriteBatch &b = g.batch; + static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"}; for (const Fighter &f : fighters) { - Vec2 p = lerp(f.previous, f.position, alpha); - Rect box = f.pushbox().translated(p - f.position); - box = {std::round(box.x), std::round(box.y), box.w, box.h}; - b.drawRectOutline(box, hexColor(0x50e070ff), 1.0f, 8.0f); - b.drawRect({std::round(p.x) - 3, std::round(p.y), 7, 1}, hexColor(0xffffffff), 8.0f); - b.drawRect({std::round(p.x), std::round(p.y) - 3, 1, 7}, hexColor(0xffffffff), 8.0f); - char label[64]; - std::snprintf(label, sizeof label, "%s %d\nVX %.0f VY %.0f", stateName(f.state), f.stateTime, - static_cast(f.velocity.x + 0.0f), static_cast(f.velocity.y + 0.0f)); // +0:-0を0に / +0 turns -0 into 0 - // 3×5の小さな文字は影なし、暗い下地の上に / the tiny 3 × 5 font without a shadow, on a dark plate + for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 8.0f); + Rect push = f.pushbox(); + b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 8.1f); + const FrameBoxes &fb = (*g.frameData)[f.frame]; + // 攻撃判定:持続フレームの間ずっと。当たった後(もう当たらない)は薄く / the attack box for the whole active + // window; fainter once it has hit (it cannot hit again) + if (f.phase() == MovePhase::Active && fb.hit) + b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 8.2f); + for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) { + Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing); + b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 8.3f); + } + char label[96]; + if (f.state == FighterState::Attack) + std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime, + f.move->total(), kPhase[static_cast(f.phase())]); + else std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health); + // 左の人の札は左へ、右の人の札は右へずらす(近づいても重ならない) / the left fighter's label goes left, the + // right one's right (no overlap at close range) + const Fighter &other = &f == &fighters[0] ? fighters[1] : fighters[0]; + bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && &f == &fighters[0]); Vec2 size = g.tiny.measure(label); - Vec2 at = {std::round(p.x), std::round(box.y) - 16.0f}; - b.drawRect({std::round(at.x - size.x * 0.5f) - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, - {0.11f, 0.09f, 0.15f, 0.8f}, 8.5f); - g.tiny.draw(b, label, at, {.color = hexColor(0xfff4d8ff), .align = TextAlign::Centre, .layer = 9.0f}); + float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f); + Vec2 at = {x0, std::round(push.y) - 16.0f}; + 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); + g.tiny.draw(b, label, at, {.color = kText, .layer = 9.0f}); } } void FightScene::drawUi(float /*alpha*/) { - // 操作の説明(画面の下、1280×720の文字) / the controls (bottom of the screen, 1280 × 720 text) SpriteBatch &b = g.batch; b.begin(g.screen.matrix()); b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); - TextStyle s = {.color = hexColor(0xe8e0d0ff)}; - g.ui.draw(b, "1P: A D 左右・W ジャンプ・S しゃがむ 2P: カーソルキー / arrow keys F1 当たり箱 / boxes Esc 終了 / quit", - {640, 694}, {.color = s.color, .align = TextAlign::Centre}); + g.ui.draw(b, + "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L 後ろでガード / back = guard " + "F1 当たり箱 Esc 終了", + {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre}); b.end(); } diff --git a/games/fighter/src/fight_scene.hh b/games/fighter/src/fight_scene.hh index 6693950..f80f7fc 100644 --- a/games/fighter/src/fight_scene.hh +++ b/games/fighter/src/fight_scene.hh @@ -1,7 +1,8 @@ -// 対戦の場面:二人のファイター、押し合い、画面の端、道場の背景 -// The fight scene: two fighters, pushing apart, the stage edges, the dojo background +// 対戦の場面:二人のファイター、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト +// The fight scene: two fighters, pushing, hits, hit stop, health bars, effects #pragma once +#include "effects.hh" #include "fighter.hh" #include "game.hh" @@ -16,10 +17,24 @@ public: private: void separate(); + void resolveHits(); + void resetRound(); void drawBackground(); + void drawHud(); void drawDebug(float alpha); Game &g; - Camera2D camera; // 640×360のキャンバス / the 640 × 360 canvas + Camera2D camera; Fighter fighters[2]; + Effects effects; + GamepadEdges pads[2]; + int steps = 0; + int hitstop = 0; // 残りのヒットストップ(二人とも止まる) / hit stop left (both fighters frozen) + int victim = -1; // ヒットストップ中に震える方 / who shakes during the hit stop + int shake = 0; // 画面の揺れ / screen shake + int top = 0; // 手前に描くファイター(最後に攻撃した方) / the fighter drawn in front (the last attacker) + float trail[2] = {kMaxHealth, kMaxHealth}; // 体力ゲージの減っていく白い部分 / the health bar's draining trail + int trailDelay[2] = {0, 0}; + int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; // 「2 HITS」の表示 / the "2 HITS" display + int koTime = 0; // KOからの時間(練習では仕切り直す) / time since a KO (training resets) }; diff --git a/games/fighter/src/fighter.cc b/games/fighter/src/fighter.cc index 3812a4d..cf0a5c3 100644 --- a/games/fighter/src/fighter.cc +++ b/games/fighter/src/fighter.cc @@ -1,6 +1,8 @@ -// ファイター:状態機械と2Dの物理 / a fighter: the state machine and 2D physics +// ファイター:状態機械、2Dの物理、技、判定、部品のシーングラフ / a fighter: state machine, 2D physics, moves, boxes, +// the parts' scene graph #include "fighter.hh" +#include #include namespace { @@ -9,22 +11,28 @@ namespace { // steps), speeds in pixels per second constexpr float kWalkForward = 130.0f; constexpr float kWalkBack = 100.0f; -constexpr float kJumpSpeed = 560.0f; // 上向きの初速 / initial upward speed -constexpr float kJumpForward = 150.0f; // 前後ジャンプの横の速さ / horizontal speed of a forward / back jump -constexpr float kGravity = 1800.0f; // 高さ v²/2g ≈ 87 px、滞空 2v/g ≈ 0.62 s(37フレーム) / height v²/2g ≈ 87 px, - // air time 2v/g ≈ 0.62 s (37 frames) +constexpr float kJumpSpeed = 560.0f; +constexpr float kJumpForward = 150.0f; +constexpr float kGravity = 1800.0f; +constexpr float kFriction = 1400.0f; // 地上で滑るときの減速(ピクセル毎秒毎秒) / ground deceleration when sliding constexpr int kJumpSquatFrames = 4; constexpr int kLandFrames = 4; -constexpr int kCrouchInFrames = 3; // しゃがみ始めのコマを見せる時間 / how long the "going down" frame shows +constexpr int kCrouchInFrames = 3; +constexpr int kLieFrames = 40; // ダウンして寝ている時間 / how long a knocked-down fighter lies +constexpr int kGetUpFrames = 14; -// コマの原点:128×120のセルの中の足元(64, 116) / the frame origin: the feet at (64, 116) in the 128 × 120 cell constexpr Vec2 kPivot = {64.0f / 128.0f, 116.0f / 120.0f}; +constexpr float kPi = 3.14159265f; int findFrame(const SpriteSheet &sheet, const char *name) { int i = sheet.find(name); return i >= 0 ? i : 0; } +float approach(float value, float target, float amount) { + return value < target ? std::min(value + amount, target) : std::max(value - amount, target); +} + } // namespace const char *stateName(FighterState state) { @@ -35,35 +43,134 @@ const char *stateName(FighterState state) { case FighterState::JumpSquat: return "JUMPSQUAT"; case FighterState::Air: return "AIR"; case FighterState::Land: return "LAND"; + case FighterState::Attack: return "ATTACK"; + case FighterState::Hitstun: return "HITSTUN"; + case FighterState::Blockstun: return "BLOCKSTUN"; + case FighterState::Knockdown: return "KNOCKDOWN"; + case FighterState::GetUp: return "GETUP"; + case FighterState::KO: return "KO"; } return "?"; } -Fighter::Fighter(const SpriteSheet &s, std::string fighterName, Vec2 start, float startFacing) - : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), +Fighter::Fighter(const SpriteSheet &s, const SpriteSheet &effects, const FrameData &frameData, std::string fighterName, + const char *tail, Vec2 start, float startFacing) + : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData), idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")), fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), - fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")) { + fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")), + fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")), + fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) { animator.play(idleClip); frame = animator.frame(); + buildParts(effects, tail); +} + +void Fighter::reset(Vec2 start, float startFacing) { + position = previous = start; + velocity = {0.0f, 0.0f}; + facing = startFacing; + state = FighterState::Idle; + stateTime = stun = combo = 0; + health = kMaxHealth; + move = nullptr; + onGround = true; + buffer.clear(); + animator.play(idleClip, true); + frame = animator.frame(); +} + +// 体の部品の木を作る。コマ(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("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; } -// 状態を変える。同じ状態なら時間を数え続ける / changes the state; the same state keeps counting void Fighter::setState(FighterState next) { if (next == state) return; state = next; stateTime = 0; } -void Fighter::update(float dt, const Controls &c, float opponentX) { +bool Fighter::actionable() const { + return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch; +} + +// 技を始める。押したステップが発生の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; +} + +void Fighter::update(float dt, const Controls &c, float opponentX, bool threat) { + controls = c; + landed = false; + guarding = false; + time += dt; ++stateTime; switch (state) { case FighterState::Idle: case FighterState::Walk: case FighterState::Crouch: { - // 地上で自由に動ける状態:いつも相手の方を向く(ぴったり重なったら向きを変えない) - // Free on the ground: always face the opponent (keep the facing when exactly on top of each other) if (std::abs(opponentX - position.x) > 1.0f) facing = opponentX > position.x ? 1.0f : -1.0f; + if (tryMoves(c.down)) break; // 技はほかの動きより先 / moves take priority over movement bool fwd = forward(c, facing), bwd = back(c, facing); if (c.up) { jumpDirection = fwd ? 1.0f : bwd ? -1.0f : 0.0f; @@ -71,7 +178,14 @@ void Fighter::update(float dt, const Controls &c, float opponentX) { 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); } else if (fwd || bwd) { walkingBack = bwd; velocity.x = facing * (fwd ? kWalkForward : -kWalkBack); @@ -83,74 +197,242 @@ void Fighter::update(float dt, const Controls &c, float opponentX) { break; } case FighterState::JumpSquat: - // 「ため」の間はまだ地面。終わったら跳ぶ:上向きの速度と、決めた向きへの横の速度 - // Still on the ground during the squat. Then take off: an upward velocity plus the chosen horizontal one if (stateTime >= kJumpSquatFrames) { velocity = {facing * jumpDirection * kJumpForward, -kJumpSpeed}; + onGround = false; + airMoveUsed = false; setState(FighterState::Air); } break; case FighterState::Air: - velocity.y += kGravity * dt; // 重力:速度を変える(位置は下で速度から) / gravity changes the velocity (the - // position follows from the velocity below) + // 空中技は一回のジャンプで一度 / one air move per jump + if (!airMoveUsed && (buffer.take(Button::Kick) || buffer.take(Button::Punch))) { + airMoveUsed = true; + startMove(MoveId::JumpKick); + } break; case FighterState::Land: if (stateTime >= kLandFrames) setState(FighterState::Idle); break; + case FighterState::Attack: + // 地上技は全体フレームが終わったら自由に。空中技は着地で終わる(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; + case FighterState::Hitstun: + case FighterState::Blockstun: + if (--stun <= 0) setState(c.down ? FighterState::Crouch : FighterState::Idle); + break; + case FighterState::Knockdown: + if (onGround && --stun <= 0) setState(FighterState::GetUp); + break; + case FighterState::GetUp: + if (stateTime >= kGetUpFrames) setState(FighterState::Idle); + break; + case FighterState::KO: + break; } - // 半陰的オイラー法:速度を先に、その速度で位置を / semi-implicit Euler: velocity first, then the position with it + // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops + // everything except walking + if (!onGround) velocity.y += kGravity * dt; + else if (state != FighterState::Walk) velocity.x = approach(velocity.x, 0.0f, kFriction * dt); position += velocity * dt; - - // 地面:落ちてきて地面より下なら、地面に置いて着地 / the ground: when falling below it, put the fighter on it and land - if (state == FighterState::Air && velocity.y > 0.0f && position.y >= kGroundY) { + if (!onGround && velocity.y > 0.0f && position.y >= kGroundY) { position.y = kGroundY; - velocity = {0.0f, 0.0f}; - setState(FighterState::Land); + velocity.y = 0.0f; + onGround = true; + onLanding(); } chooseFrame(dt); + updateParts(dt); +} + +void Fighter::onLanding() { + landed = true; + switch (state) { + case FighterState::Air: + case FighterState::Attack: // 空中技の途中で着地 / landing during an air move + move = nullptr; + velocity.x = 0.0f; + setState(FighterState::Land); + break; + case FighterState::Knockdown: + case FighterState::KO: + velocity.x *= 0.3f; + stun = kLieFrames; + break; + default: + break; + } +} + +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; +} + +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; +} + +Rect Fighter::pushbox() const { + bool low = state == FighterState::Crouch || (state == FighterState::Attack && move && move->height == AttackHeight::Low) || + state == FighterState::KO || state == FighterState::Knockdown || state == FighterState::GetUp || + ((state == FighterState::Hitstun || state == FighterState::Blockstun) && controls.down); + // 幅は絵の胴と脚くらい(狭すぎると密着したとき体がめり込んで見える) / about as wide as the drawn torso and legs + // (too narrow and the bodies sink into each other at close range) + // 倒れている間は横に長い(体が画面の外にはみ出さない) / long and flat while lying (the body never leaves the screen) + bool lying = onGround && (state == FighterState::Knockdown || state == FighterState::KO); + Rect local = lying ? Rect{-40.0f, -24.0f, 80.0f, 24.0f} + : !onGround ? Rect{-15.0f, -86.0f, 30.0f, 58.0f} + : low ? Rect{-21.0f, -60.0f, 42.0f, 60.0f} + : Rect{-19.0f, -88.0f, 38.0f, 88.0f}; + return local.translated(position); +} + +std::vector Fighter::hurtboxes() const { + std::vector 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 Fighter::activeHitbox() const { + if (phase() != MovePhase::Active || moveHit) return std::nullopt; + const std::optional &hit = data[frame].hit; + if (!hit) return std::nullopt; + return toWorld(*hit, position, facing); } -// 状態からコマを選ぶ。ループする動き(立ち・歩き)はAnimator、それ以外は状態と速度で決める -// Picks the frame from the state. Looping motions (idle, walk) use the Animator; the rest depend on state and velocity void Fighter::chooseFrame(float dt) { + bool crouched = controls.down; switch (state) { case FighterState::Idle: + if (guarding) { + frame = fBlock; + return; + } animator.play(idleClip); break; case FighterState::Walk: animator.play(walkingBack ? walkBackClip : walkClip); break; case FighterState::Crouch: - frame = stateTime < kCrouchInFrames ? fCrouchIn : fCrouch; + frame = guarding ? fCBlock : stateTime < kCrouchInFrames ? fCrouchIn : fCrouch; return; case FighterState::JumpSquat: case FighterState::Land: + case FighterState::GetUp: frame = fCrouchIn; return; case FighterState::Air: - // 上昇中・頂点の近く・落下中 / rising, near the top, falling frame = velocity.y < -180.0f ? fJumpUp : velocity.y < 180.0f ? fJumpTuck : fJumpDown; return; + 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; + } + case FighterState::Hitstun: + frame = crouched ? fCHit : stateTime < 6 ? fHit1 : fHit0; // 最初に大きくのけぞる / the big recoil comes first + return; + case FighterState::Blockstun: + frame = crouched ? fCBlock : fBlock; + return; + case FighterState::Knockdown: + case FighterState::KO: + frame = onGround ? fKo1 : fKo0; + return; } animator.update(dt); frame = animator.frame(); } -Rect Fighter::pushbox() const { - // 足元からの箱。空中は脚をたたむので下が空く(相手の上を越えられる) / boxes from the feet; in the air the legs are - // tucked, so the bottom is open (a fighter can pass over the other) - Rect local = state == FighterState::Crouch ? Rect{-15.0f, -60.0f, 30.0f, 60.0f} - : state == FighterState::Air ? Rect{-13.0f, -86.0f, 26.0f, 58.0f} - : Rect{-14.0f, -88.0f, 28.0f, 88.0f}; - return local.translated(position); +// 部品の動き(ステップごと):鉢巻の尾はばねで角度を追いかけ、星は頭の周りを回る +// 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(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; + } } -void Fighter::draw(SpriteBatch &batch, float alpha, float layer) const { - // 補間した位置を整数に丸める(ピクセルアートは整数の位置に) / the interpolated position, rounded to whole pixels +void Fighter::draw(SpriteBatch &batch, float alpha, float layer, int shake) { Vec2 p = lerp(previous, position, alpha); - Sprite s = sheet.sprite(frame, {std::round(p.x), std::round(p.y)}, kPivot); - s.flipX = facing < 0.0f; // 絵は右向き:左向きは左右反転 / the art faces right; facing left mirrors it - s.layer = layer; - batch.draw(s); + root->position = {std::round(p.x), kGroundY}; + root->scale = {facing, 1.0f}; + float shakeX = shake ? static_cast((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); } diff --git a/games/fighter/src/fighter.hh b/games/fighter/src/fighter.hh index ff010a1..7d81a6c 100644 --- a/games/fighter/src/fighter.hh +++ b/games/fighter/src/fighter.hh @@ -1,19 +1,27 @@ -// ファイター:状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理(重力・速度・地面)、コマ送りのアニメーション -// A fighter: a state machine (idle, walk, crouch, jump), 2D physics (gravity, velocity, the ground) and frame -// animation +// ファイター:状態機械、2Dの物理、技(フレームデータ)、食らい・攻撃判定、体の部品のシーングラフ +// A fighter: the state machine, 2D physics, moves (frame data), hurt / hit boxes, a scene graph of body parts #pragma once #include "controls.hh" +#include "frame_data.hh" +#include "input_buffer.hh" +#include "moves.hh" +#include "scene_graph.hh" #include "engine/animation.hh" #include "engine/rect.hh" #include "engine/sprite_batch.hh" #include "engine/sprite_sheet.hh" +#include +#include +#include #include +#include // キャンバスは640×360(画面に2倍)。足元のy座標 / the canvas is 640 × 360 (×2 on screen). The y of the feet constexpr float kGroundY = 320.0f; +constexpr int kMaxHealth = 100; // 状態。どの状態でも「何ステップ目か」(stateTime)を数える:格闘ゲームの時間はフレーム数 // The states. Every state counts its steps (stateTime): in fighting games time is measured in frames @@ -21,47 +29,105 @@ enum class FighterState { Idle, // 立ち / standing Walk, // 歩き(前・後ろ) / walking (forwards or backwards) Crouch, // しゃがみ / crouching - JumpSquat, // 跳ぶ前のため(数フレーム、まだ地面) / the crouch before take-off (a few frames, still on the ground) - Air, // 空中(放物線、空中では向きも軌道も変えられない) / in the air (a parabola; neither facing nor arc can - // change) - Land, // 着地の硬さ(数フレーム動けない) / landing recovery (a few frames without control) + JumpSquat, // 跳ぶ前のため / the crouch before take-off + Air, // 空中 / in the air + Land, // 着地の硬さ / landing recovery + Attack, // 技を出している(発生 → 持続 → 硬直) / performing a move (startup → active → recovery) + Hitstun, // のけぞり(動けない) / reeling from a hit (no control) + Blockstun, // ガードの硬直 / guarding (no control) + Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up + GetUp, // 起き上がり(無敵) / getting up (invincible) + KO, // 体力0:倒れたまま / health 0: stays down }; const char *stateName(FighterState state); +enum class HitResult { Hit, Blocked, KO }; + +// 技の今の段階 / where a move currently is +enum class MovePhase { None, Startup, Active, Recovery }; + class Fighter { public: - Fighter(const SpriteSheet &sheet, std::string name, Vec2 start, float facing); + // sheet:ファイターのコマ、effects:尾・星・影、tail:鉢巻の尾のコマ名 / sheet: the fighter's frames, effects: + // tails, stars, shadow; tail: the headband tail's frame name + Fighter(const SpriteSheet &sheet, const SpriteSheet &effects, const FrameData &data, std::string name, + const char *tail, Vec2 start, float facing); + // 練習の仕切り直し:体力・状態・位置を戻す / a training reset: health, state and position back to the start + void reset(Vec2 start, float startFacing); - // 1ステップ(1/60秒)進める。opponentXで相手の方を向く / advances one step (1/60 s); faces the opponent at opponentX - void update(float dt, const Controls &controls, float opponentX); - // ステップの最初に呼ぶ:描くときの補間用に今の位置を覚える / call at the start of a step: remembers the position - // for interpolation when drawing + // 1ステップ(1/60秒)進める。threat = 相手が近くで技を出している(後ろを押すと下がらずに構える) + // Advances one step (1/60 s). threat = the opponent is attacking nearby (holding back then guards in place + // instead of walking away: "proximity guard") + void update(float dt, const Controls &controls, float opponentX, bool threat); void savePrevious() { previous = position; } - // 押し合いの箱(ワールド座標):二人が重ならないための箱 / the push box (world): keeps the two fighters apart Rect pushbox() const; - void draw(SpriteBatch &batch, float alpha, float layer) const; - // 前を押しているか(向きに対して) / is "forward" held (relative to the facing) + // 食らい判定(ワールド)。無敵なら空 / hurt boxes (world); empty while invincible + std::vector hurtboxes() const; + // 攻撃判定(ワールド):持続フレームで、まだ当たっていないときだけ / the attack box (world): only during active + // frames and before it has hit + std::optional activeHitbox() const; + MovePhase phase() const; + // 今の入力でこの技をガードできるか(後ろを押している、高さが合う、ガードできる状態) + // Can the current input block this move (holding back, the right height, a state that can block) + bool canBlock(AttackHeight height, float attackerX) const; + // 当てられた:体力・状態・ノックバック。attackerFacingの向きに押される / got hit: health, state, knockback; pushed + // in attackerFacing's direction + HitResult takeHit(const MoveData &move, float attackerFacing, bool blocked); + 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); } + bool actionable() const; + + // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them + void draw(SpriteBatch &batch, float alpha, float layer, int shake); static bool forward(const Controls &c, float facing) { return facing > 0.0f ? c.right : c.left; } static bool back(const Controls &c, float facing) { return facing > 0.0f ? c.left : c.right; } std::string name; - Vec2 position; // 足元の中心(ワールドのピクセル、y下向き) / the feet center (world pixels, y down) - Vec2 previous; // 前のステップの位置 / last step's position - Vec2 velocity; // ピクセル毎秒 / pixels per second - float facing = 1.0f; // +1 = 右向き、-1 = 左向き / +1 = facing right, -1 = facing left + Vec2 position, previous, velocity; + float facing = 1.0f; FighterState state = FighterState::Idle; - int stateTime = 0; // この状態で何ステップ目か / steps spent in this state + int stateTime = 0; + int frame = 0; + int health = kMaxHealth; + int stun = 0; // のけぞり・ガード硬直の残り / hit stun / block stun left + int combo = 0; // 連続で食らった数 / hits taken in the current combo + const MoveData *move = nullptr; + MoveId moveId = MoveId::Punch; + bool moveHit = false; bool walkingBack = false; - int frame = 0; // 今のコマ(スプライトシートの番号) / the current frame (sprite-sheet index) + bool guarding = false; // 構えている(近くの攻撃に後ろを押している) / holding a guard against a nearby attack + bool landed = false; // このステップで着地した(砂ぼこり用) / landed this step (for dust) + InputBuffer buffer; + Controls controls; // このステップの入力(ガードの判定に) / this step's input (for blocking) private: void setState(FighterState next); + void startMove(MoveId id); + bool tryMoves(bool crouching); + void onLanding(); void chooseFrame(float dt); + void buildParts(const SpriteSheet &effects, const char *tail); + void updateParts(float dt); const SpriteSheet &sheet; + const FrameData &data; const AnimationClip *idleClip, *walkClip, *walkBackClip; Animator animator; - float jumpDirection = 0.0f; // -1 後ろ、0 垂直、+1 前 / -1 back, 0 straight up, +1 forwards - int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown; + float jumpDirection = 0.0f; + bool onGround = true; + bool airMoveUsed = false; + float time = 0.0f; + int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1; + + // シーングラフ:root(足元、向きで左右反転)→ 影、body(コマ)→ 頭のソケット → 星、結び目 → 尾1 → 尾2 + // The scene graph: root (the feet, mirrored by facing) → shadow, body (the frame) → head socket → stars, + // knot → tail 1 → tail 2 + std::unique_ptr root; + Node *shadow, *body, *head, *stars, *knot, *tail1, *tail2; + Node *starNodes[3]; + float tailAngle[2] = {3.0f, 3.0f}, tailSpeed[2] = {0.0f, 0.0f}; // 尾の世界の角度(右向きの空間で) / the tails' + // angles (in facing-right space) }; diff --git a/games/fighter/src/frame_data.cc b/games/fighter/src/frame_data.cc new file mode 100644 index 0000000..3b126a9 --- /dev/null +++ b/games/fighter/src/frame_data.cc @@ -0,0 +1,60 @@ +// コマごとの判定データ / per-frame box data +#include "frame_data.hh" + +#include "engine/file_util.hh" + +#include +#include + +std::optional FrameData::load(const std::string &path, const SpriteSheet &sheet) { + std::optional text = readTextFile(path); + if (!text) return std::nullopt; + FrameData data; + data.frames.resize(static_cast(sheet.count())); + std::istringstream lines(*text); + std::string line; + int number = 0; + while (std::getline(lines, line)) { + ++number; + std::istringstream in(line); + std::string kind, frameName; + if (!(in >> kind) || kind[0] == '#') continue; + in >> frameName; + int index = sheet.find(frameName); + if (index < 0) { + fprintf(stderr, "%s:%d: コマがない / unknown frame '%s'\n", path.c_str(), number, frameName.c_str()); + return std::nullopt; + } + FrameBoxes &f = data.frames[static_cast(index)]; + if (kind == "hurt" || kind == "hit") { + Rect r; + if (!(in >> r.x >> r.y >> r.w >> r.h)) { + fprintf(stderr, "%s:%d: x y w h が要る / expected x y w h\n", path.c_str(), number); + return std::nullopt; + } + if (kind == "hurt") f.hurt.push_back(r); + else f.hit = r; + } else if (kind == "socket") { + std::string name; + Vec2 p; + if (!(in >> name >> p.x >> p.y)) { + fprintf(stderr, "%s:%d: name x y が要る / expected name x y\n", path.c_str(), number); + return std::nullopt; + } + if (name == "head") f.head = p; + else if (name == "knot") f.knot = p; + else if (name == "fist") f.fist = p; + else if (name == "foot") f.foot = p; + } else { + fprintf(stderr, "%s:%d: 知らない行 / unknown line '%s'\n", path.c_str(), number, kind.c_str()); + return std::nullopt; + } + } + return data; +} + +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}; +} diff --git a/games/fighter/src/frame_data.hh b/games/fighter/src/frame_data.hh new file mode 100644 index 0000000..7922ab3 --- /dev/null +++ b/games/fighter/src/frame_data.hh @@ -0,0 +1,32 @@ +// コマごとの判定データ(fighter.boxes):食らい判定、攻撃判定、部品を付ける位置(ソケット) +// Per-frame box data (fighter.boxes): hurt boxes, the attack box, and where parts attach (sockets) +#pragma once + +#include "engine/rect.hh" +#include "engine/sprite_sheet.hh" + +#include +#include +#include + +// 足元からの位置、右向き、y下向き(ピクセル) / relative to the feet, facing right, y down (pixels) +struct FrameBoxes { + std::vector hurt; // 食らい判定(ここに当たるとやられる) / hurt boxes (getting hit here hurts) + std::optional 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 x y w h | hit x y w h | socket x y | # comment + // コマの名前はsheetで引く(sheetのコマ番号で並ぶ) / frame names are looked up in `sheet` (indexed like the sheet) + static std::optional load(const std::string &path, const SpriteSheet &sheet); + const FrameBoxes &operator[](int frame) const { return frames[static_cast(frame)]; } + +private: + std::vector 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); diff --git a/games/fighter/src/game.hh b/games/fighter/src/game.hh index 79b2834..5750a3e 100644 --- a/games/fighter/src/game.hh +++ b/games/fighter/src/game.hh @@ -2,6 +2,8 @@ // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) #pragma once +#include "frame_data.hh" + #include "engine/camera2d.hh" #include "engine/font.hh" #include "engine/game_loop.hh" @@ -22,6 +24,8 @@ struct Game { const Font &pixel; // pixel12:キャンバスの中 / inside the canvas const Font &tiny; // pixel5:デバッグ表示 / debug labels const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) + const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow + const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton) Camera2D screen; // 1280×720のUI / the 1280 × 720 UI bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels }; diff --git a/games/fighter/src/input_buffer.hh b/games/fighter/src/input_buffer.hh new file mode 100644 index 0000000..d86671d --- /dev/null +++ b/games/fighter/src/input_buffer.hh @@ -0,0 +1,35 @@ +// 入力バッファ:ボタンを押してから数フレームの間、その入力を覚えておく。硬直が解けた瞬間に技が出る +// 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(b)]; + if (a > kWindow) return false; + a = kNone; + return true; + } + bool waiting(Button b) const { return age[static_cast(b)] <= kWindow; } + void clear() { age[0] = age[1] = kNone; } + +private: + static constexpr int kNone = 1000; + int age[2] = {kNone, kNone}; +}; diff --git a/games/fighter/src/main.cc b/games/fighter/src/main.cc index 2f5598b..8e3e945 100644 --- a/games/fighter/src/main.cc +++ b/games/fighter/src/main.cc @@ -2,12 +2,18 @@ // // 第30章:ファイターの状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理、コマ送りのアニメーション、二人の入力 // Chapter 30: the fighter state machine (idle, walk, crouch, jump), 2D physics, frame animation, two players' input +// 第31章:技(フレームデータ)、攻撃・食らい判定、ダメージ、のけぞり、ノックバック、ヒットストップ、体力ゲージ、 +// 入力バッファ、体の部品とエフェクトのシーングラフ +// Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input +// buffering, a scene graph for body parts and effects // // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): -// 1P A D 前後・W ジャンプ・S しゃがみ / A D walk, W jump, S crouch -// 2P ← → 前後・↑ ジャンプ・↓ しゃがみ / arrow keys -// ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック) / gamepads: 1st = 1P, 2nd = 2P (d-pad or left stick) -// F1 押し合いの箱と状態 / push boxes and states Esc 終了 / quit +// 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick +// 2P ← → ↑ ↓、K 突き・L 蹴り(テンキーの1・2でも) / arrow keys, K punch, L kick (or keypad 1, 2) +// 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching) +// ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P, +// 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick) +// F1 判定の箱と状態 / boxes and states Esc 終了 / quit #include "fight_scene.hh" #include "game.hh" @@ -29,7 +35,12 @@ int main() { // frame layout, different colors (a palette swap) std::optional hayate = SpriteSheet::loadAtlas("games/fighter/assets/hayate.atlas"); std::optional jin = SpriteSheet::loadAtlas("games/fighter/assets/jin.atlas"); - if (!batch || !ui || !pixel || !tiny || !hayate || !jin) return 1; + std::optional effects = SpriteSheet::loadAtlas("games/fighter/assets/effects.atlas"); + if (!batch || !ui || !pixel || !tiny || !hayate || !jin || !effects) return 1; + // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton: + // the same for both (same frame names and indices) + std::optional frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate); + if (!frameData) return 1; Input input; input.attach(window); @@ -38,7 +49,7 @@ int main() { GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); PixelCanvas canvas(static_cast(kViewSize.x), static_cast(kViewSize.y)); Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel, - .tiny = *tiny, .fighters = {&*hayate, &*jin}, .screen = Camera2D::screen({1280.0f, 720.0f})}; + .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .screen = Camera2D::screen({1280.0f, 720.0f})}; SceneManager scenes; scenes.push(std::make_unique(game)); diff --git a/games/fighter/src/moves.cc b/games/fighter/src/moves.cc new file mode 100644 index 0000000..ae46802 --- /dev/null +++ b/games/fighter/src/moves.cc @@ -0,0 +1,33 @@ +// 技の性能表 / the move table +#include "moves.hh" + +namespace { + +// 有利不利(当てた後どちらが先に動けるか)= 相手の硬直 −(持続の残り + 自分の硬直)。最初の持続フレームで当てた場合: +// 突き:ヒット 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}, +}; +static_assert(sizeof(kMoves) / sizeof(kMoves[0]) == static_cast(MoveId::Count)); + +} // namespace + +const MoveData &moveData(MoveId id) { return kMoves[static_cast(id)]; } diff --git a/games/fighter/src/moves.hh b/games/fighter/src/moves.hh new file mode 100644 index 0000000..a340ce2 --- /dev/null +++ b/games/fighter/src/moves.hh @@ -0,0 +1,26 @@ +// 技の性能表(フレームデータ):発生・持続・硬直、ダメージ、のけぞり、ガード硬直、ヒットストップ、ノックバック +// 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); diff --git a/games/fighter/src/scene_graph.cc b/games/fighter/src/scene_graph.cc new file mode 100644 index 0000000..ea83baf --- /dev/null +++ b/games/fighter/src/scene_graph.cc @@ -0,0 +1,66 @@ +// 2Dのシーングラフ / the 2D scene graph +#include "scene_graph.hh" + +#include +#include + +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}; +} + +Affine2 operator*(const Affine2 &a, const Affine2 &b) { + // bの軸をaの線型部分で変換し、bの原点をaで変換する / b's axes through a's linear part, b's origin 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)}; +} + +Node &Node::add(std::string childName) { return add(std::make_unique(std::move(childName))); } + +Node &Node::add(std::unique_ptr child) { + children.push_back(std::move(child)); + return *children.back(); +} + +void Node::remove(const Node *child) { + std::erase_if(children, [child](const std::unique_ptr &c) { return c.get() == child; }); +} + +Node *Node::find(std::string_view childName) { + for (auto &c : children) { + if (c->name == childName) return c.get(); + if (Node *n = c->find(childName)) return n; + } + return nullptr; +} + +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; +} + +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); +} diff --git a/games/fighter/src/scene_graph.hh b/games/fighter/src/scene_graph.hh new file mode 100644 index 0000000..e01add3 --- /dev/null +++ b/games/fighter/src/scene_graph.hh @@ -0,0 +1,72 @@ +// 2Dのシーングラフ:親子の変換(位置・回転・拡大)を持つノードの木。キャラクターの部品とエフェクトに使う +// A 2D scene graph: a tree of nodes with parent-child transforms (position, rotation, scale), used for character +// parts and effects +// +// 考え方は第14章のglTFのノードと同じ:world = parent.world × local。違いは2D(2×3の行列)だけ +// The same idea as chapter 14's glTF nodes: world = parent.world × local. Only 2D (a 2 × 3 matrix) +// +// メモ:エンジンに移してもよい(ゲームに依存しない) / note: could move into the engine later (nothing game-specific) +#pragma once + +#include "engine/sprite_batch.hh" + +#include +#include +#include +#include +#include + +// 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); + +// ノード:ローカルの変換、描くスプライト(なくてもよい)、子供たち。子は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 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; + std::vector> children; +}; + +// ワールドの変換をSpriteBatchのSprite(位置・大きさ・回転・左右反転)に直す。鏡に映した変換(行列式 < 0)は +// flipXと、左右を入れ替えたoriginで表す +// Turns a world transform into a SpriteBatch Sprite (position, size, rotation, flipX). A mirrored transform +// (determinant < 0) becomes flipX plus a horizontally swapped origin +Sprite toSprite(const Sprite &sprite, const Affine2 &world);