30. 2D格闘ゲーム パート1:キャラクターと2D物理
スペースインベーダーの次、パート6の2つ目のゲームは、3章掛けて作る2D格闘ゲームです。
スペースインベーダーはプレイヤーが一人、自機が1機、そしてタイマーで行進する隊列でした。
格闘ゲームは其の逆です。
一台のキーボードに二人のプレイヤー、其々が小さな状態の機械になっている二人のキャラクター、そしていつも全く同じ様に感じられなければならない動きです。
プレイヤーは動きをフレーム単位で覚えるからです。
此のパート1では、二人のファイターが歩き、しゃがみ、跳べる様になります。
自分で相手の方を向き、相手をすり抜けずに押し、ステージから出ません。
攻撃はまだありません。
其れは当たり判定とダメージと一緒に第31章で入ります。
パート6の他のゲームと同じく、使うのは第25章と第26章のエンジンだけなので、新しいOpenGLの関数はありません。
面白い所は、状態機械、数行の物理、そして絵です。
キャラクター一人に38枚のコマがあり、全部プログラムが骨格から描いた物です。
30.1 此の章で作る物
プログラムfighterは道場での練習モードです。
左にハヤテ(1P、白い道着に赤い鉢巻)、右にジン(2P、紺の道着に黄色い鉢巻)がいます。
動画では、二人が歩き、垂直ジャンプと前ジャンプをし、片方が相手を飛び越えて二人とも振り向き、片方がジャンプの下でしゃがみ、又離れて行きます:
二人で一台のキーボードを使います:
| 動作 | 1P(ハヤテ) | 2P(ジン) |
|---|---|---|
| 前後に歩く | A、D | ←、→ |
| ジャンプ(前か後ろを押しながらで前ジャンプ・後ろジャンプ) | W | ↑ |
| しゃがむ | S | ↓ |
| デバッグ表示(押し合いの箱、状態、速度) | F1 | F1 |
| 終了 | Esc | Esc |
ゲームパッドも使えます。
1台目が1P、2台目が2Pで、十字キー又は左スティックで動かします。
此の章の物は全部新しく、games/fighter/の中にあります。
其のフォルダの外は何も変わりません:
games/fighter/CMakeLists.txt:実行ファイルfightersrc/main.cc:ウィンドウ、共有の資源、ループ、フレームsrc/game.hh:シーンが共有するGameの文脈src/controls.hh、src/controls.cc:一人分の入力を小さな構造体にする。キーとゲームパッドからsrc/fighter.hh、src/fighter.cc:Fighter。状態機械、物理、コマ、押し合いの箱src/fight_scene.hh、src/fight_scene.cc:道場、二人のファイター、押し合い、画面の端、デバッグ表示assets/hayate.png、hayate.atlas、jin.png、jin.atlas:二人のスプライトシート、及びassets/LICENSE.txt(完成したファイルは章のZIPとアセットのZIPのch30/に入っています)README.md:動かし方とキーの表
CMakeのファイルは、どのゲームも使う雛形です:
# 2D格闘ゲーム(第30〜32章):エンジンにリンクする自分の実行ファイル
# The 2D fighting game (chapters 30-32): its own executable linking the engine
add_executable(fighter
src/main.cc
src/controls.cc
src/fighter.cc
src/fight_scene.cc)
target_include_directories(fighter PRIVATE src)
target_link_libraries(fighter PRIVATE engine)
enable_warnings(fighter)
set_working_directory(fighter)
第26章の一番上のCMakeLists.txtは既にgames/fighter/CMakeLists.txtを探すので、CMakeを実行し直すだけです。
LinuxとFreeBSDでは、プロジェクトのルートから./build/games/fighter/fighterで動かします。
Visual Studioではfighterをスタートアッププロジェクトにします(実行ファイルはbuild\games\fighter\Debug\fighter.exeで、set_working_directoryが作業ディレクトリをプロジェクトのルートにします)。
30.2 大きなキャンバス:640 × 360
スペースインベーダーは320 × 180のキャンバスを4倍にして描きました。
ファイターには其れでは小さ過ぎます。
高さ180ピクセルでは、キャラクターは50 px位の高さになり、腕の太さは3、4ピクセルです。
拳、曲がった膝、そして第31章の手足ごとの当たり判定には足りません。
其の為、格闘ゲームのキャンバスは640 × 360で、1280 × 720のウィンドウに2倍で描きます。
此れも整数倍なので、キャンバスの1ピクセルは丁度画面の2 × 2ピクセルになり、ファイターは100 px位の高さに出来ます。
大きさは、シーンが共有する物と一緒に、ゲームの文脈の構造体に置きます(第26章のデモと同じ考えです):
// 仮想解像度:640×360(1280×720に2倍)。ファイターが大きく描ける / the virtual resolution: 640 × 360 (×2 in
// 1280 × 720), so the fighters can be big
constexpr Vec2 kViewSize = {640.0f, 360.0f};
struct Game {
Window &window;
Input &input;
GameLoop &loop;
SpriteBatch &batch;
const Font &ui; // mono16:1280×720のUI / the 1280 × 720 UI
const Font &pixel; // pixel12:キャンバスの中 / inside the canvas
const Font &tiny; // pixel5:デバッグ表示 / debug labels
const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P)
Camera2D screen; // 1280×720のUI / the 1280 × 720 UI
bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels
};
mainはフォントと二人のスプライトシートを読み込み、キーを割り当て、第26章のフレームの構造で動かします。
世界をキャンバスに、キャンバスを画面に、其の後UIを画面の解像度で描きます:
loop.run(
window, input,
[&](float dt) {
scenes.update(dt);
if (scenes.empty()) window.close();
},
[&](float alpha) {
// 世界は640×360のキャンバスへ(2倍で画面に)、UIは1280×720で / the world into the 640 × 360 canvas (×2 on
// screen), the UI at 1280 × 720
canvas.begin(hexColor(0x1b1726ff));
scenes.draw(alpha);
canvas.present(window.width(), window.height());
letterbox(window.width(), window.height(), game.screen.viewSize, false).apply();
scenes.drawUi(alpha);
scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize);
});
ループは第26章のGameLoopで、ステップは1/60秒です。
格闘ゲームでは、此の固定ステップは単に「有った方が良い」物ではありません。
此のジャンルは時間を1/60秒のフレームで数えるので、此のゲームでは「60 Hz」と「1フレーム」は同じ意味で、此の先の時間の長さは全てフレームで書きます。
30.3 ファイター:骨格から作るコマ
此れがハヤテのシート全体です。
輪郭が見える様に青い背景の上に重ねてあります:
シートは1040 × 610で、128 × 120のセルが38個、8列に並び、第25章の1ピクセルの余白と2ピクセルの隙間があります。
此の章で使うのは最初の15枚(立ち、歩き、しゃがみ、3つのジャンプ)だけです。
攻撃、防御、やられ、勝ちのコマは第31章の為に既に入っています。
ジンのシートは同じコマが同じ場所に色違いで入っているパレットスワップで、多くのアーケードゲームの2Pキャラクターと同じです。
従って、コマを説明するデータ(名前、第31章の当たり判定の箱)は二人で共有出来ます。
コマの作り方
此れらは誰も1ピクセルずつ描いていません。
あたしの自作のPythonのスクリプトが作った物です。
ゲームが要るのは其の出力だけなので、スクリプトはプロジェクトのダウンロードには入っていません。
スクリプトはファイターを小さな2Dの骨格として表します。
腰、傾ける角度を持つ胴、頭、そして2本ずつの骨を持つ2本の脚と2本の腕です。
ポーズは数個の数字だけです。
腰の位置、胴の傾き、2つの足と2つの拳を置きたい場所で、全部両足の間の点からの相対位置です。
膝と肘はポーズに全く入っていません。
スクリプトが2本の骨のインバースキネマティクス(IK)で求めます。
此れは直ぐ後で見ます。
次に、手足を1本ずつ、先細りのカプセルの繋がりとしてアンチエイリアス無しでラスタライズします(カプセルとは、線分からある半径以内にある点の集まりです)。
各ピクセルは、其の面が左上からの光の方をどれだけ向いているかで、材質(道着、肌、髪、鉢巻、帯)の3つの階調の1つになります。
滑らかなグラデーションではなく、はっきりした段で塗るセルシェーディングです。
5つの材質に3階調ずつ、其れにシリーズの全てのスプライトが使う共通の暗い輪郭の色(27, 23, 38)です。
手足は遠い側から描きます。
遠い腕、遠い脚、胴、近い脚、頭、近い腕の順です。
各グループは重ねる時に自分の1ピクセルの輪郭を貰うので、胸の前の近い腕は、自分と胸の間に暗い線を描きます。
丁度絵描きが線を引く場所です。
遠い手足は近い手足より1段暗い階調を使い、其れで遠い脚が「後ろにある」様に見えます。
3つのポーズを3倍に拡大し、骨格を重ねた物です:
黄色い関節がスクリプトが解いた物です。
kick1では近い足の目標が前の遠く、相手の腹の高さにあり、目標が脚の届く範囲の外(股関節から約51 pxで、太腿と脛を合わせた46 pxより遠い)なので、脚は真っ直ぐに伸び切ります(此の場合の扱いは下で見ます)。
骨格から絵を作る事には、ゲームにとって大きな利点が2つあります。
1つ目は、新しいポーズが数字1行で済み、体の比率やパレットを変えれば全てのコマが揃って作り直される事です。
2つ目は、第31章にとってもっと大事な事で、同じ骨格が全てのコマで拳と足の位置を正確に知っているので、スクリプトはピクセルを描いたのと同じデータから当たり判定と食らい判定の箱を書き出せます。
絵と判定のデータが食い違う事は有り得ません。
大きなスタジオも、もっと大きな規模で同じ事をしています。
例えばDead Cellsは3Dのモデルを動かし、其れをピクセルアートのコマにレンダリングしています。
ゲーム自体は此の事を何も知りません。
見えるのは普通のスプライトシートだけです。
2本の骨のIK
問題はこうです。
脚には長さ pxの太腿と、長さ pxの脛があります。
股関節はにあり、足はに置きたい。
膝はどこでしょうか?
3つの点は三角形を作り、其の3辺の長さが分かっています。
、、そして距離です(線型代数シリーズの第3章)。
3辺で三角形は決まるので、要るのは腰での角度、目標への線と太腿の間の角度だけです。
其れが余弦定理で、線型代数シリーズの第4章の内積を三角形について書き下した物です。
(太腿)ととすると、脛はなので
従って
腰から目標への向きの角度はで、膝は其の向きをだけ片側に回した方向に、太腿の長さだけ進んだ所です:
符号は、鏡に映した様な2つの解のどちらにするかを選びます。
前に曲がる膝か、後ろに曲がる膝かです。
どの三角形にも解は2つあるので、IKにはいつも此の1つの選択が要ります。
スクリプトはをの少し手前で切り詰めるので、届かない目標には、1より大きい数のarccosではなく、目標の方を向いた真っ直ぐな脚になります。
此れはidle0の近い脚で、足元を原点、y下向きのスプライトのピクセルで表しています。
股関節は、足首は前の足の裏の3 px上、に置きたいとします:
- なので、。
- なので、。(2本の骨が同じ長さなら、式はに縮みます。)
- で、なら太腿はを向きます。
- 。
yが下向きなので、角度を小さくすると画面上では反時計回り、+xの方に回ります。
其の為で膝が前に来ます。
普通の膝です。
脛はからの方へ伸び、目標が届く範囲なので丁度其処で終わります。
肘も同じで、上腕16 px、前腕15 pxで、反対向きに曲げます。
3Dのリアルタイムのスケルタルアニメーションも、でこぼこの地面に足を置いたり、出っ張りに手を掛けたりするのに正に此の解き方を使います。
普通は私達のの代わりに、膝が向く方向を示す「ポールベクトル」を使います。
アトラスと原点
スクリプトはシートと一緒に第25章のアトラスファイルを書き出します:
# hayate: fighter frames 128x120, feet pivot at (64, 116), facing right (generated by the author's own script)
image hayate.png
sprite idle0 1 1 128 120
sprite idle1 131 1 128 120
...
sprite jump_down 781 123 128 120
...
clip idle 7 loop idle0 idle1 idle2 idle3
clip walk 10 loop walk0 walk1 walk2 walk3 walk4 walk5
clip walk_back 10 loop walk5 walk4 walk3 walk2 walk1 walk0
clip win 4 loop win0 win1
大事な決まりは原点(ピボット)です。
どのセルでも、ポーズに関係無く、ファイターの両足の間の点が(64, 116)にあります。
しゃがみのコマもジャンプのコマも同じ大きさで、体がセルの中の違う高さにあるだけです。
其の為ゲームは、ファイターの位置を「両足の間の点」として扱い、全てのコマを同じ原点で描き、コマが変わっても何もずらす必要がありません。
原点のxはセルの真ん中なので、30.8で見る様に左右反転もただで出来ます。
walk_backは歩きを逆に再生した物で、有り得る中で一番安い、其れらしい後ろ歩きです。
30.4 操作:ファイターが知って良い事
ファイター本体の前に、其の入力です。
ファイターはキーを読みません。
ステップごとに小さな構造体を1つ受け取ります:
// 1ステップ分の入力。方向は押している間、ファイターはこれだけを見る(キーもパッドも知らない)
// One step of input. Directions are "held". The fighter only sees this (it knows nothing about keys or pads)
struct Controls {
bool left = false, right = false, up = false, down = false;
};
// 一人分のキー(GLFW_KEY_…) / one player's keys (GLFW_KEY_...)
struct PlayerKeys {
int left, right, up, down;
};
// 1P:WASD、2P:矢印キー / 1P: WASD, 2P: the arrow keys
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},
};
此の分け方は3回役に立ちます。
第32章ではコンピューターの相手が同じControlsを埋めてジンを動かし、ファイターのコードは全く変わりません。
ステップごとのControlsを記録した列は、試合を正確に再生します。
ゲームが決定的(第26章の固定ステップと種を決めたRng)だからです。
そして此れは、今の格闘ゲームがオンラインで遊ぶ方法、ロールバックのネットコードの土台になる形です。
ネットワークを通るのは入力だけで、各マシンが其処から同じゲームをシミュレーションします。
キーは第26章の名前付きの行動"p1.left"〜"p2.down"を通り、bindPlayerActionsで割り当てます。
一人分の操作を読むのは、actionHeldを4回、ゲームパッド、そして決まりを1つです:
Controls readControls(const Input &input, int player) {
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);
// 左右同時は「どちらでもない」(格闘ゲームの決まり:SOCD) / left + right together = neither (the fighting-game
// rule for simultaneous opposite directions, "SOCD")
if (c.left && c.right) c.left = c.right = false;
return c;
}
キーボードではAとDを同時に押せますが、レバーでは出来ません。
格闘ゲームのプレイヤーは此れをSOCD(simultaneous opposite cardinal directions、反対方向の同時入力)と呼びます。
レバーの代わりにボタンを使うコントローラーについて、大会のルールは普通、左 + 右を「どちらでもない」として扱う事を求めます。
此処でも同じにします。
上 + 下には決まりは要りません。
状態機械が上を先に調べるので、上が勝ちます。
ゲームパッド
ゲームパッドの部分は、GLFWがバージョン3.3で加えたゲームパッドのAPIを使います:
// ゲームパッド(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) {
int jid = GLFW_JOYSTICK_1 + player;
GLFWgamepadstate pad;
if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) return;
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;
}
GLFWの普通のジョイスティックの関数は、生の軸とボタンを返し、其の番号は機器とOSで違います。
ゲームパッドの関数は其の上にマッピングを載せるので(GLFWは有志が管理するSDLのゲームコントローラーのデータベースの写しを持っています)、GLFW_GAMEPAD_BUTTON_DPAD_LEFTはXboxのパッドでもPlayStationのパッドでも、殆どの他のパッドでも十字キーの左です:
glfwJoystickIsGamepad(jid)は、ジョイスティックjid(GLFW_JOYSTICK_1〜GLFW_JOYSTICK_16)がつながっていてマッピングがある時にtrueを返します。マッピングの無い機器もジョイスティックではありますが、ゲームパッドではありません。glfwUpdateGamepadMappingsで同じデータベースの形式の文字列からマッピングを足せます。glfwGetGamepadState(jid, &state)はGLFWgamepadstateに15個のbuttons(GLFW_PRESS又はGLFW_RELEASE)と6個のaxes(−1〜1)を入れ、マッピングされたゲームパッドが無ければfalseを返します。其の為、上の関数はパッドが無ければ何もしません。- スティックのy軸は「下」が正で、SDLの決まりです。其の為、上は
y < -kDeadZoneです。 - ボタンや軸にはコールバックがありません。毎回読みに行きます。更新のステップごとに1回読むのは、正に私達が欲しい形です。
デッドゾーン0.5は、スティックを半分倒すまでは数えないと云う事です。
其の為、真ん中から少しずれて止まっているスティックで歩き出す事はありません。
結果はキーボードの結果にORで足すので、キーとパッドを同時に使えます。
1つ正直に言っておかなければならない事があります。
此の部分は試せていません。
此のシリーズのスクリーンショットと動画を作るヘッドレスのテスト環境にはジョイスティックが無いので、其処ではglfwJoystickIsGamepadはいつもfalseです。
コードは小さく、GLFWの説明書の通りですが、自分のパッドで試してみて下さい。
30.5 状態機械
ファイターはいつも丁度1つの状態にあり、状態が入力の意味を決めます。
立っている時に下を押せばしゃがみますが、ジャンプの途中で下を押しても何も起きません。
動き回るだけなら、6つの状態で足ります:
// 状態。どの状態でも「何ステップ目か」(stateTime)を数える:格闘ゲームの時間はフレーム数
// The states. Every state counts its steps (stateTime): in fighting games time is measured in frames
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)
};
Idle、Walk、Crouchは自由な状態です。
プレイヤーが操作していて、毎ステップ入力が次の状態を選び直します。
他の3つは自分で進みます。
JumpSquatは跳ぶ前の短い「ため」で、ファイターはまだ地面にいるのに、ジャンプはもう決まっている4フレームです。
Airは地面に止められるまで続き、Landは着地の後の4フレームの硬さです。
此の操作出来ない小さな隙間こそが格闘ゲームの中身です。
攻撃が入れば、着地の硬さは飛び込みに反撃出来る瞬間になります。
クラスは状態と其のカウンター、物理の値、描く為のデータを持ちます:
class Fighter {
public:
Fighter(const SpriteSheet &sheet, std::string name, Vec2 start, float facing);
// 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
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)
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
FighterState state = FighterState::Idle;
int stateTime = 0; // この状態で何ステップ目か / steps spent in this state
bool walkingBack = false;
int frame = 0; // 今のコマ(スプライトシートの番号) / the current frame (sprite-sheet index)
private:
void setState(FighterState next);
void chooseFrame(float dt);
const SpriteSheet &sheet;
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;
};
此処に幾つかの決定が見えます。
positionは両足の間の点で、y下向きのキャンバスのピクセルです。
30.3の原点です。
facingはboolではなく+1か−1です。
速度に掛けるからで、「前」はファイターがどちらを向いていてもfacing * speedです。
forwardとbackは、Controlsの画面上の向きをファイター自身の向きに変えます。
格闘ゲームでは「後ろ」は相手から離れる方向で、第31章の防御も此れで出来ます。
1枚だけのポーズのコマ番号(fCrouchIn…)はコンストラクターで名前から1回だけ探すので、updateは文字列を探しません。
フレームで数える時間
どの状態も自分のステップをstateTimeで数え、全ての長さは整数のフレームです:
// 状態を変える。同じ状態なら時間を数え続ける / changes the state; the same state keeps counting
void Fighter::setState(FighterState next) {
if (next == state) return;
state = next;
stateTime = 0;
}
updateは最初に1を足し、setStateは状態が本当に変わった時に0に戻します。
其の為、状態に入ったステップは0、次は1と数えます。
同じ状態をもう一度設定しても数え直さないので、自由な状態は毎ステップsetStateを呼んで構いません。
秒ではなくフレームで数えるのが格闘ゲームの考え方で(ためは「0.0667秒」ではなく「4フレーム」)、第26章の固定ステップでは其れが正確です。
ずれて行く浮動小数点の時間は無く、2台のマシンが同じ様に数えます。
更新
此れが状態の切り替え全体です:
void Fighter::update(float dt, const Controls &c, float opponentX) {
++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;
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;
setState(FighterState::Crouch);
} else if (fwd || bwd) {
walkingBack = bwd;
velocity.x = facing * (fwd ? kWalkForward : -kWalkBack);
setState(FighterState::Walk);
} else {
velocity.x = 0.0f;
setState(FighterState::Idle);
}
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};
setState(FighterState::Air);
}
break;
case FighterState::Air:
velocity.y += kGravity * dt; // 重力:速度を変える(位置は下で速度から) / gravity changes the velocity (the
// position follows from the velocity below)
break;
case FighterState::Land:
if (stateTime >= kLandFrames) setState(FighterState::Idle);
break;
}
// 半陰的オイラー法:速度を先に、その速度で位置を / semi-implicit Euler: velocity first, then the position with it
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) {
position.y = kGroundY;
velocity = {0.0f, 0.0f};
setState(FighterState::Land);
}
chooseFrame(dt);
}
3つの自由な状態は1つのcaseを共有し、其の中のifの順番が優先度です。
上は下に勝ち、下は歩きに勝ち、歩きは立ちに勝ちます。
其の為、下と前を押すと歩かずにしゃがみ、上と下を押すと跳びます。
ジャンプの向きは、上を見たステップで、其の瞬間に押している方向から決まり、jumpDirectionに覚えます。
其の後ジャンプは確定します。
JumpSquatもAirも操作を全く見ないので、空中で舵は取れず、自由な状態に戻るまで向きも固定です。
此れが此のジャンルの昔からの決まりで、意図した設計です。
ジャンプの始まりを見た相手は着地点が分かり、反応出来ます。
其れが飛び込みを読める物にしています。
(課題2で別のやり方を試せます。)
Landは4フレームの間操作を無視し、其の後Idleに戻ります。
次のステップで自由な状態が操作をもう一度読むので、上を押しっぱなしにすれば、硬さが終わると直ぐに又跳びます。
30.6 2Dの物理:速度、重力、地面
調整の値はfighter.ccの一番上にあります:
// 動きの数値。時間はフレーム(60 Hzのステップ)、速さはピクセル毎秒 / movement tuning. Times in frames (60 Hz
// 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 int kJumpSquatFrames = 4;
constexpr int kLandFrames = 4;
constexpr int kCrouchInFrames = 3; // しゃがみ始めのコマを見せる時間 / how long the "going down" frame shows
速さはピクセル毎秒でdtを掛けるので、ステップが固定でも自然に読めます。
毎秒130 pxは前に1フレーム2.17 px、毎秒100 pxは後ろに1フレーム1.67 pxです。
殆どの格闘ゲームで後ろ歩きは前歩きより遅くなっています。
下がる事がただであってはいけないからです。
物理はupdateに散らばった3行です。
重力が速度を変え(Airの時だけ)、速度が位置を変え、地面が落下を止めます。
順番が大事です。
速度を先に、其の新しい速度で位置を、が半陰的オイラー法で、第26章が安定性の例で使った積分法です。
素朴な順番と手間は同じで、ばねや軌道でも安定しているので、ゲームの物理の定番です。
地面は当たり判定の箱ではなく、1つの数字kGroundY = 320で、キャンバスの下から40 px上です。
空中で下に動いていて(yが下向きなのでvelocity.y > 0)、其の線に着いたか越えたファイターは、丁度線の上に置かれ、止まり、Landになります。
落ちている事を確かめるので、着地だけが数えられます。
まだ上に動いているファイターが床に引き戻される事はありません。
数字の結果
一定の重力の下の動きは放物線です。
上向きに px/sで始まり、重力が px/s²のジャンプでは、連続の式は
で、コードのコメントの通りです。
但し、ゲームは連続の放物線をシミュレーションしているのではなく、1/60秒のステップをシミュレーションしていて、第26章で見た様にステップの頂点は少し高くなります。
跳ぶステップは重力無しで丸々 px動き、其の後は速度が反転するまで1ステップごとに毎秒30 px()遅くなります。
ファイターは毎秒560、530、…、20 pxの19ステップで昇ります:
第26章の近似 pxとほぼ一致します。
87.1との違いは問題ではありません。
大事なのは、ステップが固定なので、どのマシンでも、毎回91.8 pxになる事です。
上を見たステップを0フレーム目として数えると:
- 0〜3フレーム目:JumpSquat。地面の上で
crouch_inのコマ。 - 4フレーム目:跳ぶ。9.3 px上。
- 22フレーム目:頂点、91.8 px。
- 4〜41フレーム目:Air、38フレーム。デバッグ表示ではAIR 0〜AIR 37と数えます。
- 42フレーム目:地面に戻ってLand 0。42〜45フレーム目が着地の硬さ。
- 46フレーム目:又Idle。上を押していれば、次のステップ(47フレーム目)で次のジャンプが始まります(Landから出るステップは操作を読みません)。
前ジャンプは1ステップに150/60 = 2.5 pxずつ39ステップ(跳ぶステップ、空中の37、着地のステップ)動き、合わせて97.5 pxです。
30.7 コマを選ぶ
物理の後、chooseFrameがどの絵を見せるかを決めます。
2種類の動きに2つの違うやり方が要ります:
// 状態からコマを選ぶ。ループする動き(立ち・歩き)は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) {
switch (state) {
case FighterState::Idle:
animator.play(idleClip);
break;
case FighterState::Walk:
animator.play(walkingBack ? walkBackClip : walkClip);
break;
case FighterState::Crouch:
frame = stateTime < kCrouchInFrames ? fCrouchIn : fCrouch;
return;
case FighterState::JumpSquat:
case FighterState::Land:
frame = fCrouchIn;
return;
case FighterState::Air:
// 上昇中・頂点の近く・落下中 / rising, near the top, falling
frame = velocity.y < -180.0f ? fJumpUp : velocity.y < 180.0f ? fJumpTuck : fJumpDown;
return;
}
animator.update(dt);
frame = animator.frame();
}
繰り返す動き、立ちの呼吸と歩きは、アトラスのクリップを第25章のAnimatorで再生します。
既に再生中のクリップでplayを呼んでも何もしないので、毎ステップ呼んでも周期は滑らかに続きます。
walkとwalk_backの間(又はidleへ)切り替えると、新しいクリップが最初のコマから始まります。
アニメーターは物理と同じ固定のdtで進むので、アニメーションも他の全てと同じく決定的です。
其れ以外は、時計ではなく、状態、フレームのカウンター、速度から選びます。
しゃがみは、stateTimeがkCrouchInFrames(3)未満の間、つまりしゃがみの最初の3フレーム(0、1、2)は途中のcrouch_inのポーズを見せ、其の後完全なcrouchになります。
ためと着地もcrouch_inを使い、踏み切りと着地の衝撃の両方を見せます。
空中では、ポーズは縦の速度に従います。
毎秒180 pxより速く昇っている間はjump_up、頂点の辺りは膝を抱えたjump_tuck、毎秒180 pxより速く落ちる時はjump_downです。
速度はAIR 0の−560から1ステップに毎秒30 pxずつ変わるので、膝を抱えたポーズはAIR 13(毎秒−170 px)からAIR 24(毎秒+160 px)まで、38フレームの内の12フレームで、上のグラフでは17〜28フレーム目です。
ポーズを物理に結び付けておくと、もっと高いジャンプ(課題1)でも、アニメーションのデータを足さずに正しい時に正しいポーズになります。
30.8 ファイターを描く
原点の決まりのおかげで、描くのは短いです:
void Fighter::draw(SpriteBatch &batch, float alpha, float layer) const {
// 補間した位置を整数に丸める(ピクセルアートは整数の位置に) / the interpolated position, rounded to whole pixels
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);
}
と
// コマの原点: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};
Sprite::originはスプライトの大きさに対する割合なので(第25章)、(64/128, 116/120)でセルの原点のピクセルが丁度positionに来ます。
位置は第26章の補間で、前のステップと今のステップの間をalphaで結びます。
線型代数シリーズの第2章の線型補間です。
FightSceneは毎ステップの最初に二人のsavePrevious()を呼びます。
其の後、位置をキャンバスの整数のピクセルに丸めます。
キャンバスは整数倍で画面に描かれるので、端数のある位置でピクセルアートがぼやけたり不揃いになったりはしません。
ラスタライザーの丸め方次第で、スプライト全体が1ピクセルどちらかにずれるだけです。
自分で丸めるとどちらにするかがはっきりし、同じ様に丸める影とデバッグの箱が、いつもスプライトと揃います。
絵は右向きで、左を向いたファイターはflipXで反転します。
スプライトの反転はテクスチャ座標を入れ替え、絵をセルの真ん中で鏡に映します。
原点のxが丁度真ん中(128の内の64)なので、足元は同じ場所に留まり、ずらす必要はありません。
原点が真ん中からずれていたら、振り向く度にファイターが其の差の2倍だけ横に跳びます。
2Dゲームのよくあるバグです。
30.9 対戦の場面
FightSceneは二人のファイターを持ち、1ステップを進めます:
void FightScene::update(float dt) {
Input &in = g.input;
if (in.pressed(GLFW_KEY_ESCAPE)) {
scenes().pop(); // 最後のシーン:終了 / the last scene: quit
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)};
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]);
separate();
}
微妙な所は公平さです。
ファイターは1Pから順番に更新されます。
もしジンが、ハヤテが此のステップで既に動いた後の位置を読んだら、ジンはハヤテが持っていなかった情報に反応する事になり、二人は少し違うゲームを遊ぶ事になります。
其の為、先に二人の入力を読み、二人の最初の位置を写し、各ファイターはステップの最初の相手の位置の方を向きます。
其の後で動かし、最後に押し離します。
攻撃が出来る様になると、同じ決まりがもっと大事になります。
1ステップの両方の攻撃を、どちらかがダメージを受ける前に調べないと、相打ち(同じフレームで両方が当たる)がいつも1Pの勝ちになってしまいます。
向き
振り向きは自由な状態の一部で、30.5のcaseの最初の行です。
相手が1 pxより多く反対側に行くと、facingが反転します。
1ピクセルの遊びは、二人が丁度真上に重なった時のちらつきを防ぎます。
自由な状態だけが振り向くので、相手を飛び越えるジャンプは昔からのめくりになります。
地上のファイターはジャンプした相手が頭の上を越えた途端に振り向きますが、跳んだ方は着地の硬さが終わるまで元の方を向いたままで、其の後で振り向きます。
攻撃が入ると、此れがめくり攻撃を防ぎにくくします。
途中で「後ろ」が反対側に変わるからです。
30.10 押し合いの箱と画面の端
二人のファイターは互いの中に立ってはいけません。
其々が押し合いの箱を持っています。
二人の体を離す為だけにある長方形です。
殴られる箱(其れは第31章の食らい判定)ではなく、壁や床にも使いません。
二人のファイターを固く感じさせる一番簡単な物です:
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);
}
箱は足元からの相対位置で書き(上が負)、第25章のRect::translatedでファイターの位置に動かします。
しゃがみの箱は低く、少し広いので、しゃがんだファイターの上はジャンプで越え易くなります。
面白いのは空中の箱です。
ジャンプのポーズでは脚をたたんでいるので、箱は足元から28 px上から始まります。
立ちの箱は88 pxの高さまであるので、跳んだ方の足が地面から px上に来れば、其の箱を越えます。
しゃがみの箱(60 px)の上なら pxで足ります。
30.6のグラフから、ジャンプは23フレーム(11〜33フレーム目)の間60 px以上の高さにあり、其の間に前ジャンプは23 × 2.5 = 57.5 px進みます。
2つの箱がすれ違うのに要る、両側 pxずつより少し多いです。
其の為、相手の近くから始めた前ジャンプは相手を飛び越え、遠くから始めると相手の前に着地します。
ジンを立たせたままステップのコードをシミュレーションすると、境目は二人の足元の間が約76 pxの所でした。
押し離す
二人が動いた後、separateが重なりを解きます:
void clampToStage(Fighter &f) {
Rect b = f.pushbox();
if (b.left() < kStageLeft) f.position.x += kStageLeft - b.left();
if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight;
}
// 押し合い:箱が重なったら半分ずつ離す。片方が壁で止まったら、もう片方がその分も下がる
// 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);
clampToStage(b);
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
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;
}
先ず二人をステージ、x = 16から624の帯に収めます。
640 pxのキャンバスから両側16 pxの余白を引いた物で、ファイターが画面の縁に触れる事はありません。
其の後で押し合いの箱が重なっていれば(第26章のoverlaps)、重なりはxの方向の共通部分の幅で、其々が其の半分だけ相手から離れます。
変わるのはxだけでyは変わりません。
ファイターは横に押し合い、高さは重力だけが決めます。
重なりを等しく分けるので、相手に向かって歩くと相手を押す事になります。
ハヤテが1フレーム2.17 pxで立っているジンに向かって歩けば、二人とも1フレーム1.08 pxずつ動きます。
相手に向かう前歩きは半分の速さになり、相手を引きずって行きます。
二人のxが全く同じなら(めくりの後で有り得ます)、向きは「aが後ろへ」になります。
画面の端にいるファイターは下がれないので、半分ずつ動かした後でもう一度二人を収め、壁が片方から押し返した分を、もう片方に渡します。
其の為、端に追い詰めた相手に向かって歩くと、二人が重なるのではなく、相手の押し合いの箱で止められます。
格闘ゲームの「画面端の攻め」は全て此処から始まります。
壁の補正daとdbは、どちらかを渡す前に両方とも測ります。
bをaの補正で動かした後でbの補正を測ると、其の中にaの補正も入ってしまい、aは自分の補正をもう一度受け取ります。
すると端に追い詰められたファイターが其の分だけ壁から引き離され、二人の押し合いの箱も同じだけ重なった儘になります:追い詰められたハヤテにジンが歩いて行く試しの実行では毎ステップ1.08 px、上のコードではぴったり0です。
此れは殆どの2D格闘ゲームが取るやり方で、質量や力積を使う本当の衝突応答ではありません。
簡単で、すり抜けが起きず(箱は毎ステップ調べ直します)、設計者が状態ごとに調整する数字は箱の大きさだけです。
作っていて学んだ事が1つあります。
押し合いの箱は、見えている胴と脚の幅と同じ位にするべきです。
絵より狭いと、向かい合って立った二人が目に見えて互いにめり込み、設計通りに動いていてもバグに見えます。
30.11 道場とデバッグ表示
背景はSpriteBatch::drawRectの呼び出しだけで出来ています。
暗い梁、漆喰の壁、格子の障子、12 pxのピクセルフォントを2倍にして「練習」と書いた掛け軸、木の腰板、下に行く程高くなる床板(安上がりな遠近の気配)です。
40行程の長方形で、1行ずつ読む価値はありません。
第32章で視差のあるレイヤーを持つスクロールするステージに置き換えます。
各ファイターは床に半透明の長方形3つの影を持ち、影は地面の上の幅44 pxからジャンプの頂点の28 pxまで縮みます。
ファイターは背景と影より上のレイヤー2と3に描かれるので(第25章のSpriteSort::Layer)、重なった時はいつもジンがハヤテの前に描かれます。
F1でデバッグ表示を切り替えます。
状態機械には最初の日から此れが欲しくなります:
各ファイターは、押し合いの箱を緑で、足元に白い十字を、そして状態、フレームのカウンター、速度のラベルを出します。
数字で物理を確かめられます。
AIR 7でVY −350なのはだからで、AIR 31でVY 370なのはだからです。
ラベルは第26章の小さな3 × 5のpixel5フォントで、影無しで暗い下地の上に描きます。
此の大きさでは1ピクセルの影で文字が読めなくなります。
ラベルのコードの小さな所を1つ:速度−0.0を%.0fで出すと-0になるので、先に0.0fを足して−0を+0にしています。
30.12 プラットフォームごとの注意
- 全て: 多くのキーボードは、3つ以上のキーを同時に押した全ての組み合わせを報告出来ません(ゴースト、キーロールオーバーの制限)。片方のプレイヤーがキーを押している間にもう片方のキーが無視される様なら、其れはキーボードの配線で、ゲームではありません。どの組み合わせが駄目かはキーボード次第です。Nキーロールオーバーをうたうキーボードか、ゲームパッド2台なら起きません。
- 全て: 第26章と同じく、GLFWのキーコードは米国配列のキーボードでの位置なので、AZERTYのキーボードでは1PのキーはZ、Q、S、Dと書かれたキーになります。左手の下の同じ場所です。
- Windows(Visual Studio): XInputのパッド(Xbox)や殆どの他のパッドは、GLFWの内蔵のマッピングで動きます。
fighterをスタートアッププロジェクトにすると、デバッガーがプロジェクトのルートで起動します。 - Linux: GLFWはジョイスティックをカーネルのevdevのデバイス(
/dev/input/event*)から読み、デスクトップのシステムではログインしているユーザーに其のアクセス権があります。パッドを差してもglfwJoystickPresentがfalseのままなら、其れらのデバイスの権限を確かめて下さい。 - FreeBSD: GLFWがジョイスティックを見られるかどうかは、GLFWのパッケージのビルドの仕方とシステムのevdevの対応次第です。キーボードはどちらでも動きます。上に書いた通り、ゲームパッドはどのプラットフォームでも試せていません。
30.13 本物の格闘ゲームではどうしているか
- フレームデータ: 格闘ゲームは正に私達が使った数字を公開しています。ため、滞空時間、着地の硬さを60 Hzのフレームで。プレイヤーは其れを覚え、大会は画面に関係無くゲームが毎秒丁度60回更新される事に頼っています。
- 状態機械: 市販の格闘ゲームはキャラクター一人に数百の状態を持ち、普通はC++のswitchではなくデータで定義します(各状態がアニメーション、フレームごとの箱、どの入力でどの状態にキャンセル出来るかを持ちます)。構造は同じで、変わるのはデータの形式です。
- 押し合いの箱: 言葉も仕組みも定番です。殆どのゲームはアニメーションのフレームごとに箱を縮めたり動かしたりし、画面端には、追い詰められたファイターがジャンプで逃げられる様な特別な決まりを足しています。
- 絵の作り方: Dead Cellsは動く3Dのモデルをピクセルアートのコマにレンダリングしています。GUILTY GEAR Xrdと其の後継は更に進んで、セルシェーディングの3Dモデルをリアルタイムで描き、わざと低いフレームレートで動かして手描きの2Dの様に見せています。私達の骨格のスクリプトは、1つ目のやり方のとても小さな版です。
- オンライン対戦: 今の格闘ゲームはロールバックのネットコードを使います(GGPOが広めました)。各マシンは相手の入力を予想し、本物の入力が数フレーム遅れて届くと、ゲームの状態を巻き戻してシミュレーションし直します。此れは、入力全体がプレイヤーごと・フレームごとの小さな構造体である決定的なゲームでしか動きません。正に
Controlsと固定ステップがくれる物です。
30.14 まとめ
- ゲーム:
fighter、第25〜26章のエンジンの上の、games/fighter/にある自分の実行ファイル。640 × 360のキャンバスを2倍にするので、ファイターは100 px位の高さに出来る。新しいOpenGLの関数は無し。 - 骨格から作る絵: 各コマはポーズ(腰、傾き、足、拳)。膝と肘は2本の骨のIK。先細りのカプセル、3階調のセルシェーディング、輪郭、遠い手足を先に暗く。二人は同じ38枚のコマのパレットスワップ。同じ骨格が第31章の当たり判定と食らい判定の箱をくれる。
- 2本の骨のIK: 3辺の長さから、余弦定理、膝はの方向。が曲げる側を選び、は届く範囲に切り詰める。
- 原点: どのセルでも足元が(64, 116)。位置は足元、originは(64/128, 116/120)で、真ん中の原点なら
flipXの反転はただ。 - 操作: ファイターが見るのはステップごとの
Controls {left, right, up, down}だけ。名前付きのキーの行動とGLFW 3.3のゲームパッドのAPI(テスト環境では未検証)から埋める。左 + 右は中立(SOCD)、上は下に勝つ。 - 状態機械: Idle、Walk、Crouchは自由(入力が決め、相手の方を向く)。JumpSquat(4フレーム)、Air、Land(4フレーム)は自分で進む。時間はフレームで数える
stateTime。setStateは本当に変わった時だけ0に戻す。 - 物理: 固定の60 Hzで半陰的オイラー法、重力は空中だけ、地面は1つのy。毎秒560 pxと毎秒毎秒1800 pxで、理論では87.1 px、シミュレーションでは91.8 px、空中38フレーム、どのマシンでも同じ。ジャンプは向きが確定する。
- コマ: 繰り返す動きは
Animator、其れ以外は状態、フレームのカウンター、速度から選ぶ。 - 公平さ: 先に二人の入力と最初の位置を読み、其れから更新し、最後に押し離す。
- 押し合いの箱: 状態ごと(立ち、しゃがみ、めくれる様に28 px持ち上げた空中の箱)。重なりはxの方向に半分ずつ分け、画面の端で収め、追い詰められたファイターは押しを相手に渡す(壁の補正は両方を先に測ってから入れ替えて渡す)。
30.15 課題
- ★
kGravityを3600、kJumpSpeedを790にして下さい。先に連続の高さと滞空時間を計算します。高さはほぼ同じ( px)で、時間はずっと短く(0.62秒ではなく0.44秒)なります。ゲームではジャンプがきびきびし、デバッグ表示はLANDの前にAIR 37ではなくAIR 26までしか数えないはずです。 - ★ 空中での操作を足して下さい。Airのcaseで、(
facingに対して)前か後ろを押している間、velocity.xを毎秒毎秒±600 px ×dtだけ変え、毎秒±150 pxで抑えます。前を押しっぱなしの垂直ジャンプは、0ではなく77.5 px前に着地するはずで、動画のめくりも後ろを引けば取り消せます。其れから、何故殆どの格闘ゲームが此れを禁じているのか考えて下さい。 - ★ 30.10の押し合いの箱では、立っている相手を越えるには60 pxの高さが要ります。持ち上げを無くして下さい(空中の箱を
{-13, -86, 26, 86}にします)。30.6のグラフの高さから、ジャンプが88 pxより高いのは8フレームだけ、前に20 pxなので、前ジャンプは立っている相手をもう越えられませんが、しゃがんだ相手ならまだ越えられる(60 pxより高いのが23フレーム)はずです。両方をゲームで確かめて下さい。 - ★★ 前ダッシュを足して下さい。12フレーム以内に前を2回押すと新しい状態
Dashになり、6フレームの間毎秒320 pxで動いてIdleに戻ります。方向ごとに小さな押した履歴が要ります(Controlsは「押している」しか言わないので、前のステップのControlsを取っておいて、押した瞬間を自分で見つけます)。第31章の入力バッファも同じ考えから育ちます。ダッシュは6 × 320 / 60 = 32 px進むはずです。 - ★★
g.loop.setStep(1.0 / 10.0)を呼び、lerp(previous, position, alpha)で描くのとpositionをそのまま描くのを比べて下さい。補間無しではファイターは13 px(10 Hzで毎秒130 pxの歩き)ずつ目に見えて跳んで動き、補間有りでは1ステップ遅れて滑らかに動くはずです。ジャンプの形も変わります。10 Hzでは1ステップに毎秒180 pxずつ失い、頂点は91.8 pxではなく56 + 38 + 20 + 2 = 116 pxになります。正に此れが、ゲームの処理を別のステップで動かしてはいけない理由です。 - ★★ 3つの長方形の影を、Pythonで作った楕円のスプライト(48 × 8の塗り潰した楕円の画像、輪郭の色で35 %のアルファ)に置き換え、高さと共に幅を縮め、アルファをジャンプの頂点で0.35から0.15に薄くして下さい。影は柔らかく見え、其れでもピクセルアート(楕円の中にアンチエイリアス無し)のままのはずです。
- ★★★ 8方向のゲートで、アナログスティックの斜めを確実にして下さい。2つの別々のデッドゾーンの代わりに、
std::atan2(y, x)でスティックの角度と長さを求め、0.5未満は無視し、45°の8つの扇形(各方向は其の軸の周り±22.5°)に分けます。下後ろや上前は、スティックを斜めに倒した時に丁度出て、うっかり真っ直ぐな方向になる事は無くなるはずです。此れは試すのに本物のゲームパッドが要ります。
ファイル: /dev/null | b/games/fighter/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,11 @@ | |||
| 1 | # 2D格闘ゲーム(第30〜32章):エンジンにリンクする自分の実行ファイル | ||
| 2 | # The 2D fighting game (chapters 30-32): its own executable linking the engine | ||
| 3 | add_executable(fighter | ||
| 4 | src/main.cc | ||
| 5 | src/controls.cc | ||
| 6 | src/fighter.cc | ||
| 7 | src/fight_scene.cc) | ||
| 8 | target_include_directories(fighter PRIVATE src) | ||
| 9 | target_link_libraries(fighter PRIVATE engine) | ||
| 10 | enable_warnings(fighter) | ||
| 11 | set_working_directory(fighter) | ||
ファイル: /dev/null | b/games/fighter/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,21 @@ | |||
| 1 | # Fighter(2D格闘ゲーム / 2D fighting game, chapters 30-32) | ||
| 2 | |||
| 3 | プロジェクトのルートから実行 / Run from the project root: | ||
| 4 | |||
| 5 | ```sh | ||
| 6 | ./build/games/fighter/fighter # Linux / FreeBSD | ||
| 7 | build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target) | ||
| 8 | ``` | ||
| 9 | |||
| 10 | ## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard) | ||
| 11 | |||
| 12 | | | 1P | 2P | | ||
| 13 | |---|---|---| | ||
| 14 | | 前後に歩く / walk | A D | ← → | | ||
| 15 | | ジャンプ / jump (+ 前・後ろ / forward, back) | W | ↑ | | ||
| 16 | | しゃがむ / crouch | S | ↓ | | ||
| 17 | |||
| 18 | ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック)。 | ||
| 19 | Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick). | ||
| 20 | |||
| 21 | F1 押し合いの箱と状態の表示 / push boxes and states, Esc 終了 / quit. | ||
ファイル: /dev/null | b/games/fighter/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,7 @@ | |||
| 1 | games/fighter/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。 | ||
| 2 | The files in games/fighter/assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose. | ||
| 3 | |||
| 4 | hayate.png/.atlas 1Pのファイター「ハヤテ」(白い道着、128×120のコマ38枚) / player 1's fighter "Hayate" (white gi, | ||
| 5 | 38 frames of 128 × 120) (chapter 30) | ||
| 6 | jin.png/.atlas 2Pのファイター「ジン」(紺の道着、同じコマ割りの色違い) / player 2's fighter "Jin" (indigo gi, the | ||
| 7 | same frames in other colors) (chapter 30) | ||
ファイル: /dev/null | b/games/fighter/assets/hayate.atlas
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,44 @@ | |||
| 1 | # hayate: fighter frames 128x120, feet pivot at (64, 116), facing right (generated by the author's own script) | ||
| 2 | image hayate.png | ||
| 3 | sprite idle0 1 1 128 120 | ||
| 4 | sprite idle1 131 1 128 120 | ||
| 5 | sprite idle2 261 1 128 120 | ||
| 6 | sprite idle3 391 1 128 120 | ||
| 7 | sprite walk0 521 1 128 120 | ||
| 8 | sprite walk1 651 1 128 120 | ||
| 9 | sprite walk2 781 1 128 120 | ||
| 10 | sprite walk3 911 1 128 120 | ||
| 11 | sprite walk4 1 123 128 120 | ||
| 12 | sprite walk5 131 123 128 120 | ||
| 13 | sprite crouch_in 261 123 128 120 | ||
| 14 | sprite crouch 391 123 128 120 | ||
| 15 | sprite jump_up 521 123 128 120 | ||
| 16 | sprite jump_tuck 651 123 128 120 | ||
| 17 | sprite jump_down 781 123 128 120 | ||
| 18 | sprite punch0 911 123 128 120 | ||
| 19 | sprite punch1 1 245 128 120 | ||
| 20 | sprite punch2 131 245 128 120 | ||
| 21 | sprite kick0 261 245 128 120 | ||
| 22 | sprite kick1 391 245 128 120 | ||
| 23 | sprite kick2 521 245 128 120 | ||
| 24 | sprite sweep0 651 245 128 120 | ||
| 25 | sprite sweep1 781 245 128 120 | ||
| 26 | sprite sweep2 911 245 128 120 | ||
| 27 | sprite jkick0 1 367 128 120 | ||
| 28 | sprite jkick1 131 367 128 120 | ||
| 29 | sprite cpunch0 261 367 128 120 | ||
| 30 | sprite cpunch1 391 367 128 120 | ||
| 31 | sprite cpunch2 521 367 128 120 | ||
| 32 | sprite block 651 367 128 120 | ||
| 33 | sprite cblock 781 367 128 120 | ||
| 34 | sprite hit0 911 367 128 120 | ||
| 35 | sprite hit1 1 489 128 120 | ||
| 36 | sprite chit 131 489 128 120 | ||
| 37 | sprite ko0 261 489 128 120 | ||
| 38 | sprite ko1 391 489 128 120 | ||
| 39 | sprite win0 521 489 128 120 | ||
| 40 | sprite win1 651 489 128 120 | ||
| 41 | clip idle 7 loop idle0 idle1 idle2 idle3 | ||
| 42 | clip walk 10 loop walk0 walk1 walk2 walk3 walk4 walk5 | ||
| 43 | clip walk_back 10 loop walk5 walk4 walk3 walk2 walk1 walk0 | ||
| 44 | clip win 4 loop win0 win1 | ||
ファイル: /dev/null | b/games/fighter/assets/hayate.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/assets/jin.atlas
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,44 @@ | |||
| 1 | # jin: fighter frames 128x120, feet pivot at (64, 116), facing right (generated by the author's own script) | ||
| 2 | image jin.png | ||
| 3 | sprite idle0 1 1 128 120 | ||
| 4 | sprite idle1 131 1 128 120 | ||
| 5 | sprite idle2 261 1 128 120 | ||
| 6 | sprite idle3 391 1 128 120 | ||
| 7 | sprite walk0 521 1 128 120 | ||
| 8 | sprite walk1 651 1 128 120 | ||
| 9 | sprite walk2 781 1 128 120 | ||
| 10 | sprite walk3 911 1 128 120 | ||
| 11 | sprite walk4 1 123 128 120 | ||
| 12 | sprite walk5 131 123 128 120 | ||
| 13 | sprite crouch_in 261 123 128 120 | ||
| 14 | sprite crouch 391 123 128 120 | ||
| 15 | sprite jump_up 521 123 128 120 | ||
| 16 | sprite jump_tuck 651 123 128 120 | ||
| 17 | sprite jump_down 781 123 128 120 | ||
| 18 | sprite punch0 911 123 128 120 | ||
| 19 | sprite punch1 1 245 128 120 | ||
| 20 | sprite punch2 131 245 128 120 | ||
| 21 | sprite kick0 261 245 128 120 | ||
| 22 | sprite kick1 391 245 128 120 | ||
| 23 | sprite kick2 521 245 128 120 | ||
| 24 | sprite sweep0 651 245 128 120 | ||
| 25 | sprite sweep1 781 245 128 120 | ||
| 26 | sprite sweep2 911 245 128 120 | ||
| 27 | sprite jkick0 1 367 128 120 | ||
| 28 | sprite jkick1 131 367 128 120 | ||
| 29 | sprite cpunch0 261 367 128 120 | ||
| 30 | sprite cpunch1 391 367 128 120 | ||
| 31 | sprite cpunch2 521 367 128 120 | ||
| 32 | sprite block 651 367 128 120 | ||
| 33 | sprite cblock 781 367 128 120 | ||
| 34 | sprite hit0 911 367 128 120 | ||
| 35 | sprite hit1 1 489 128 120 | ||
| 36 | sprite chit 131 489 128 120 | ||
| 37 | sprite ko0 261 489 128 120 | ||
| 38 | sprite ko1 391 489 128 120 | ||
| 39 | sprite win0 521 489 128 120 | ||
| 40 | sprite win1 651 489 128 120 | ||
| 41 | clip idle 7 loop idle0 idle1 idle2 idle3 | ||
| 42 | clip walk 10 loop walk0 walk1 walk2 walk3 walk4 walk5 | ||
| 43 | clip walk_back 10 loop walk5 walk4 walk3 walk2 walk1 walk0 | ||
| 44 | clip win 4 loop win0 win1 | ||
ファイル: /dev/null | b/games/fighter/assets/jin.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/src/controls.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,54 @@ | |||
| 1 | // 一人分の操作 / one player's controls | ||
| 2 | #include "controls.hh" | ||
| 3 | |||
| 4 | namespace { | ||
| 5 | |||
| 6 | // 行動の名前(プレイヤーごと) / action names per player | ||
| 7 | struct ActionNames { | ||
| 8 | const char *left, *right, *up, *down; | ||
| 9 | }; | ||
| 10 | constexpr ActionNames kActions[2] = { | ||
| 11 | {"p1.left", "p1.right", "p1.up", "p1.down"}, | ||
| 12 | {"p2.left", "p2.right", "p2.up", "p2.down"}, | ||
| 13 | }; | ||
| 14 | |||
| 15 | // ゲームパッド(GLFW 3.3以上のSDL互換マッピング):十字キーか左スティック。つながっていなければ何もしない | ||
| 16 | // A gamepad (GLFW 3.3+'s SDL-style mapping): the d-pad or the left stick. Does nothing when none is connected | ||
| 17 | void addGamepad(int player, Controls &c) { | ||
| 18 | int jid = GLFW_JOYSTICK_1 + player; | ||
| 19 | GLFWgamepadstate pad; | ||
| 20 | if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) return; | ||
| 21 | constexpr float kDeadZone = 0.5f; | ||
| 22 | 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; | ||
| 24 | c.right |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT] == GLFW_PRESS || x > kDeadZone; | ||
| 25 | c.up |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP] == GLFW_PRESS || y < -kDeadZone; | ||
| 26 | c.down |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN] == GLFW_PRESS || y > kDeadZone; | ||
| 27 | } | ||
| 28 | |||
| 29 | } // namespace | ||
| 30 | |||
| 31 | void bindPlayerActions(Input &input) { | ||
| 32 | for (int p = 0; p < 2; ++p) { | ||
| 33 | const PlayerKeys &k = kPlayerKeys[p]; | ||
| 34 | const ActionNames &a = kActions[p]; | ||
| 35 | input.bind(a.left, {InputBinding::key(k.left)}); | ||
| 36 | input.bind(a.right, {InputBinding::key(k.right)}); | ||
| 37 | input.bind(a.up, {InputBinding::key(k.up)}); | ||
| 38 | input.bind(a.down, {InputBinding::key(k.down)}); | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | Controls readControls(const Input &input, int player) { | ||
| 43 | const ActionNames &a = kActions[player]; | ||
| 44 | Controls c; | ||
| 45 | c.left = input.actionHeld(a.left); | ||
| 46 | c.right = input.actionHeld(a.right); | ||
| 47 | c.up = input.actionHeld(a.up); | ||
| 48 | c.down = input.actionHeld(a.down); | ||
| 49 | addGamepad(player, c); | ||
| 50 | // 左右同時は「どちらでもない」(格闘ゲームの決まり:SOCD) / left + right together = neither (the fighting-game | ||
| 51 | // rule for simultaneous opposite directions, "SOCD") | ||
| 52 | if (c.left && c.right) c.left = c.right = false; | ||
| 53 | return c; | ||
| 54 | } | ||
ファイル: /dev/null | b/games/fighter/src/controls.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,30 @@ | |||
| 1 | // 一人分の操作:キーボード(一台を二人で分ける)とゲームパッド(あれば) | ||
| 2 | // One player's controls: the keyboard (one keyboard shared by two players) and a gamepad (if there is one) | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "engine/input.hh" | ||
| 6 | |||
| 7 | // 1ステップ分の入力。方向は押している間、ファイターはこれだけを見る(キーもパッドも知らない) | ||
| 8 | // One step of input. Directions are "held". The fighter only sees this (it knows nothing about keys or pads) | ||
| 9 | struct Controls { | ||
| 10 | bool left = false, right = false, up = false, down = false; | ||
| 11 | }; | ||
| 12 | |||
| 13 | // 一人分のキー(GLFW_KEY_…) / one player's keys (GLFW_KEY_...) | ||
| 14 | struct PlayerKeys { | ||
| 15 | int left, right, up, down; | ||
| 16 | }; | ||
| 17 | |||
| 18 | // 1P:WASD、2P:矢印キー / 1P: WASD, 2P: the arrow keys | ||
| 19 | constexpr PlayerKeys kPlayerKeys[2] = { | ||
| 20 | {GLFW_KEY_A, GLFW_KEY_D, GLFW_KEY_W, GLFW_KEY_S}, | ||
| 21 | {GLFW_KEY_LEFT, GLFW_KEY_RIGHT, GLFW_KEY_UP, GLFW_KEY_DOWN}, | ||
| 22 | }; | ||
| 23 | |||
| 24 | // 二人分の行動をInputに登録する("p1.left"、"p2.up"…) / registers both players' actions with Input ("p1.left", | ||
| 25 | // "p2.up"...) | ||
| 26 | void bindPlayerActions(Input &input); | ||
| 27 | |||
| 28 | // キーボードの行動と、ゲームパッド(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 | ||
| 30 | Controls readControls(const Input &input, int player); | ||
ファイル: /dev/null | b/games/fighter/src/fight_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,189 @@ | |||
| 1 | // 対戦の場面(第30章:二人が動き回る練習モード) / the fight scene (chapter 30: a training mode where both move) | ||
| 2 | #include "fight_scene.hh" | ||
| 3 | |||
| 4 | #include "engine/collision.hh" | ||
| 5 | |||
| 6 | #include <algorithm> | ||
| 7 | #include <cmath> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <string> | ||
| 10 | |||
| 11 | namespace { | ||
| 12 | |||
| 13 | // 画面の端(押し合いの箱がこの外に出ない) / the stage edges (push boxes never leave them) | ||
| 14 | constexpr float kStageLeft = 16.0f; | ||
| 15 | constexpr float kStageRight = 624.0f; | ||
| 16 | |||
| 17 | // 道場の色 / the dojo's colors | ||
| 18 | constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff); | ||
| 19 | constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff); | ||
| 20 | constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff); | ||
| 21 | constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff); | ||
| 22 | constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff); | ||
| 23 | constexpr Vec4 kOutline = hexColor(0x1b1726ff); | ||
| 24 | |||
| 25 | void clampToStage(Fighter &f) { | ||
| 26 | Rect b = f.pushbox(); | ||
| 27 | if (b.left() < kStageLeft) f.position.x += kStageLeft - b.left(); | ||
| 28 | if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight; | ||
| 29 | } | ||
| 30 | |||
| 31 | } // namespace | ||
| 32 | |||
| 33 | FightScene::FightScene(Game &game) | ||
| 34 | : g(game), camera(Camera2D::screen(kViewSize)), | ||
| 35 | fighters{Fighter(*game.fighters[0], "HAYATE", {200.0f, kGroundY}, 1.0f), | ||
| 36 | Fighter(*game.fighters[1], "JIN", {440.0f, kGroundY}, -1.0f)} {} | ||
| 37 | |||
| 38 | void FightScene::update(float dt) { | ||
| 39 | Input &in = g.input; | ||
| 40 | if (in.pressed(GLFW_KEY_ESCAPE)) { | ||
| 41 | scenes().pop(); // 最後のシーン:終了 / the last scene: quit | ||
| 42 | return; | ||
| 43 | } | ||
| 44 | if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; | ||
| 45 | |||
| 46 | // 二人の入力を先に全部読み、相手の位置もステップの最初の値を使う:1Pを先に動かしても2Pが得をしない | ||
| 47 | // Read both inputs first and use the opponents' positions from the start of the step: updating 1P first gives | ||
| 48 | // neither player an advantage | ||
| 49 | Controls controls[2] = {readControls(in, 0), readControls(in, 1)}; | ||
| 50 | float startX[2] = {fighters[0].position.x, fighters[1].position.x}; | ||
| 51 | for (Fighter &f : fighters) f.savePrevious(); | ||
| 52 | for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i]); | ||
| 53 | separate(); | ||
| 54 | } | ||
| 55 | |||
| 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() { | ||
| 60 | Fighter &a = fighters[0], &b = fighters[1]; | ||
| 61 | clampToStage(a); | ||
| 62 | clampToStage(b); | ||
| 63 | Rect ra = a.pushbox(), rb = b.pushbox(); | ||
| 64 | if (!overlaps(ra, rb)) return; | ||
| 65 | 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の動く向き / | ||
| 67 | // a's direction | ||
| 68 | a.position.x += dir * overlap * 0.5f; | ||
| 69 | b.position.x -= dir * overlap * 0.5f; | ||
| 70 | float ax = a.position.x, bx = b.position.x; | ||
| 71 | clampToStage(a); | ||
| 72 | 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; | ||
| 75 | b.position.x += da; | ||
| 76 | a.position.x += db; | ||
| 77 | } | ||
| 78 | |||
| 79 | void FightScene::drawBackground() { | ||
| 80 | SpriteBatch &b = g.batch; | ||
| 81 | // 梁と漆喰の壁 / beams and the plaster wall | ||
| 82 | b.drawRect({0, 0, 640, 360}, kPlaster); | ||
| 83 | b.drawRect({0, 0, 640, 34}, kBeam); | ||
| 84 | b.drawRect({0, 34, 640, 3}, kBeamLight); | ||
| 85 | b.drawRect({0, 37, 640, 4}, kPlasterShade); | ||
| 86 | for (float x = 0; x < 640; x += 160) { | ||
| 87 | b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars | ||
| 88 | b.drawRect({x + 9, 37, 3, 200}, kBeamLight); | ||
| 89 | } | ||
| 90 | // 障子:格子の窓 / shoji: lattice windows | ||
| 91 | for (float x : {28.0f, 188.0f, 348.0f, 508.0f}) { | ||
| 92 | if (x == 188.0f) continue; // 真ん中は掛け軸 / scroll in the middle instead | ||
| 93 | Rect w = {x, 62, 104, 120}; | ||
| 94 | b.drawRect(w, kLattice); | ||
| 95 | b.drawRect({w.x + 3, w.y + 3, w.w - 6, w.h - 6}, kShoji); | ||
| 96 | for (float lx = w.x + 3 + 24; lx < w.right() - 4; lx += 25) b.drawRect({lx, w.y + 3, 2, w.h - 6}, kLattice); | ||
| 97 | for (float ly = w.y + 3 + 28; ly < w.bottom() - 4; ly += 29) b.drawRect({w.x + 3, ly, w.w - 6, 2}, kLattice); | ||
| 98 | } | ||
| 99 | // 掛け軸「練習」 / a hanging scroll: "practice" | ||
| 100 | b.drawRect({212, 52, 64, 6}, kBeam); | ||
| 101 | b.drawRect({218, 58, 52, 132}, hexColor(0xf6f0e0ff)); | ||
| 102 | b.drawRect({218, 58, 52, 4}, hexColor(0x9a4a3aff)); | ||
| 103 | b.drawRect({218, 186, 52, 4}, hexColor(0x9a4a3aff)); | ||
| 104 | b.drawRect({212, 190, 64, 6}, kBeam); | ||
| 105 | g.pixel.draw(b, "練", {244, 82}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); | ||
| 106 | 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 | ||
| 108 | // 腰板 / wainscot | ||
| 109 | b.drawRect({0, 222, 640, 38}, kWainscot); | ||
| 110 | b.drawRect({0, 222, 640, 3}, kWainscotDark); | ||
| 111 | for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark); | ||
| 112 | // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective) | ||
| 113 | float y = 260.0f; | ||
| 114 | 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}) { | ||
| 116 | b.drawRect({0, y, 640, h}, row % 2 ? kPlankA : kPlankB); | ||
| 117 | b.drawRect({0, y, 640, 1}, kPlankLine); | ||
| 118 | float offset = static_cast<float>((row * 97) % 120); | ||
| 119 | for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine); | ||
| 120 | y += h; | ||
| 121 | ++row; | ||
| 122 | } | ||
| 123 | } | ||
| 124 | |||
| 125 | void FightScene::draw(float alpha) { | ||
| 126 | SpriteBatch &b = g.batch; | ||
| 127 | b.begin(camera.matrix(), SpriteSort::Layer); | ||
| 128 | drawBackground(); | ||
| 129 | // 影:地面に。高く跳ぶほど小さく / shadows on the ground, smaller the higher the jump | ||
| 130 | for (const Fighter &f : fighters) { | ||
| 131 | Vec2 p = lerp(f.previous, f.position, alpha); | ||
| 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); | ||
| 143 | |||
| 144 | // 名前(キャンバスの中のピクセル文字) / names (pixel text inside the canvas) | ||
| 145 | TextStyle name = {.color = hexColor(0xfff4d8ff), .layer = 10.0f, .shadow = kOutline}; | ||
| 146 | b.drawRect({0, 0, 640, 22}, {0.11f, 0.09f, 0.15f, 0.55f}, 9.5f); | ||
| 147 | g.pixel.draw(b, "1P " + fighters[0].name, {12, 4}, name); | ||
| 148 | TextStyle right = name; | ||
| 149 | right.align = TextAlign::Right; | ||
| 150 | g.pixel.draw(b, fighters[1].name + " 2P", {628, 4}, right); | ||
| 151 | TextStyle centre = name; | ||
| 152 | centre.align = TextAlign::Centre; | ||
| 153 | centre.color = hexColor(0xf2c14eff); | ||
| 154 | g.pixel.draw(b, "練習 TRAINING", {320, 4}, centre); | ||
| 155 | b.end(); | ||
| 156 | } | ||
| 157 | |||
| 158 | // F1:押し合いの箱、足元、状態の名前と時間 / F1: push boxes, the feet, the state name and its time | ||
| 159 | void FightScene::drawDebug(float alpha) { | ||
| 160 | SpriteBatch &b = g.batch; | ||
| 161 | for (const Fighter &f : fighters) { | ||
| 162 | Vec2 p = lerp(f.previous, f.position, alpha); | ||
| 163 | Rect box = f.pushbox().translated(p - f.position); | ||
| 164 | box = {std::round(box.x), std::round(box.y), box.w, box.h}; | ||
| 165 | b.drawRectOutline(box, hexColor(0x50e070ff), 1.0f, 8.0f); | ||
| 166 | b.drawRect({std::round(p.x) - 3, std::round(p.y), 7, 1}, hexColor(0xffffffff), 8.0f); | ||
| 167 | b.drawRect({std::round(p.x), std::round(p.y) - 3, 1, 7}, hexColor(0xffffffff), 8.0f); | ||
| 168 | char label[64]; | ||
| 169 | std::snprintf(label, sizeof label, "%s %d\nVX %.0f VY %.0f", stateName(f.state), f.stateTime, | ||
| 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 | ||
| 171 | // 3×5の小さな文字は影なし、暗い下地の上に / the tiny 3 × 5 font without a shadow, on a dark plate | ||
| 172 | Vec2 size = g.tiny.measure(label); | ||
| 173 | Vec2 at = {std::round(p.x), std::round(box.y) - 16.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}, | ||
| 175 | {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}); | ||
| 177 | } | ||
| 178 | } | ||
| 179 | |||
| 180 | void FightScene::drawUi(float /*alpha*/) { | ||
| 181 | // 操作の説明(画面の下、1280×720の文字) / the controls (bottom of the screen, 1280 × 720 text) | ||
| 182 | SpriteBatch &b = g.batch; | ||
| 183 | b.begin(g.screen.matrix()); | ||
| 184 | b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); | ||
| 185 | TextStyle s = {.color = hexColor(0xe8e0d0ff)}; | ||
| 186 | g.ui.draw(b, "1P: A D 左右・W ジャンプ・S しゃがむ 2P: カーソルキー / arrow keys F1 当たり箱 / boxes Esc 終了 / quit", | ||
| 187 | {640, 694}, {.color = s.color, .align = TextAlign::Centre}); | ||
| 188 | b.end(); | ||
| 189 | } | ||
ファイル: /dev/null | b/games/fighter/src/fight_scene.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,25 @@ | |||
| 1 | // 対戦の場面:二人のファイター、押し合い、画面の端、道場の背景 | ||
| 2 | // The fight scene: two fighters, pushing apart, the stage edges, the dojo background | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "fighter.hh" | ||
| 6 | #include "game.hh" | ||
| 7 | |||
| 8 | #include "engine/scene.hh" | ||
| 9 | |||
| 10 | class FightScene : public Scene { | ||
| 11 | public: | ||
| 12 | explicit FightScene(Game &game); | ||
| 13 | void update(float dt) override; | ||
| 14 | void draw(float alpha) override; | ||
| 15 | void drawUi(float alpha) override; | ||
| 16 | |||
| 17 | private: | ||
| 18 | void separate(); | ||
| 19 | void drawBackground(); | ||
| 20 | void drawDebug(float alpha); | ||
| 21 | |||
| 22 | Game &g; | ||
| 23 | Camera2D camera; // 640×360のキャンバス / the 640 × 360 canvas | ||
| 24 | Fighter fighters[2]; | ||
| 25 | }; | ||
ファイル: /dev/null | b/games/fighter/src/fighter.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,156 @@ | |||
| 1 | // ファイター:状態機械と2Dの物理 / a fighter: the state machine and 2D physics | ||
| 2 | #include "fighter.hh" | ||
| 3 | |||
| 4 | #include <cmath> | ||
| 5 | |||
| 6 | namespace { | ||
| 7 | |||
| 8 | // 動きの数値。時間はフレーム(60 Hzのステップ)、速さはピクセル毎秒 / movement tuning. Times in frames (60 Hz | ||
| 9 | // steps), speeds in pixels per second | ||
| 10 | constexpr float kWalkForward = 130.0f; | ||
| 11 | constexpr float kWalkBack = 100.0f; | ||
| 12 | constexpr float kJumpSpeed = 560.0f; // 上向きの初速 / initial upward speed | ||
| 13 | constexpr float kJumpForward = 150.0f; // 前後ジャンプの横の速さ / horizontal speed of a forward / back jump | ||
| 14 | constexpr float kGravity = 1800.0f; // 高さ v²/2g ≈ 87 px、滞空 2v/g ≈ 0.62 s(37フレーム) / height v²/2g ≈ 87 px, | ||
| 15 | // air time 2v/g ≈ 0.62 s (37 frames) | ||
| 16 | constexpr int kJumpSquatFrames = 4; | ||
| 17 | constexpr int kLandFrames = 4; | ||
| 18 | constexpr int kCrouchInFrames = 3; // しゃがみ始めのコマを見せる時間 / how long the "going down" frame shows | ||
| 19 | |||
| 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}; | ||
| 22 | |||
| 23 | int findFrame(const SpriteSheet &sheet, const char *name) { | ||
| 24 | int i = sheet.find(name); | ||
| 25 | return i >= 0 ? i : 0; | ||
| 26 | } | ||
| 27 | |||
| 28 | } // namespace | ||
| 29 | |||
| 30 | const char *stateName(FighterState state) { | ||
| 31 | switch (state) { | ||
| 32 | case FighterState::Idle: return "IDLE"; | ||
| 33 | case FighterState::Walk: return "WALK"; | ||
| 34 | case FighterState::Crouch: return "CROUCH"; | ||
| 35 | case FighterState::JumpSquat: return "JUMPSQUAT"; | ||
| 36 | case FighterState::Air: return "AIR"; | ||
| 37 | case FighterState::Land: return "LAND"; | ||
| 38 | } | ||
| 39 | return "?"; | ||
| 40 | } | ||
| 41 | |||
| 42 | Fighter::Fighter(const SpriteSheet &s, std::string fighterName, Vec2 start, float startFacing) | ||
| 43 | : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), | ||
| 44 | 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")), | ||
| 46 | fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")) { | ||
| 47 | animator.play(idleClip); | ||
| 48 | frame = animator.frame(); | ||
| 49 | } | ||
| 50 | |||
| 51 | // 状態を変える。同じ状態なら時間を数え続ける / changes the state; the same state keeps counting | ||
| 52 | void Fighter::setState(FighterState next) { | ||
| 53 | if (next == state) return; | ||
| 54 | state = next; | ||
| 55 | stateTime = 0; | ||
| 56 | } | ||
| 57 | |||
| 58 | void Fighter::update(float dt, const Controls &c, float opponentX) { | ||
| 59 | ++stateTime; | ||
| 60 | switch (state) { | ||
| 61 | case FighterState::Idle: | ||
| 62 | case FighterState::Walk: | ||
| 63 | 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; | ||
| 67 | bool fwd = forward(c, facing), bwd = back(c, facing); | ||
| 68 | if (c.up) { | ||
| 69 | jumpDirection = fwd ? 1.0f : bwd ? -1.0f : 0.0f; | ||
| 70 | velocity = {0.0f, 0.0f}; | ||
| 71 | setState(FighterState::JumpSquat); | ||
| 72 | } else if (c.down) { | ||
| 73 | velocity.x = 0.0f; | ||
| 74 | setState(FighterState::Crouch); | ||
| 75 | } else if (fwd || bwd) { | ||
| 76 | walkingBack = bwd; | ||
| 77 | velocity.x = facing * (fwd ? kWalkForward : -kWalkBack); | ||
| 78 | setState(FighterState::Walk); | ||
| 79 | } else { | ||
| 80 | velocity.x = 0.0f; | ||
| 81 | setState(FighterState::Idle); | ||
| 82 | } | ||
| 83 | break; | ||
| 84 | } | ||
| 85 | 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) { | ||
| 89 | velocity = {facing * jumpDirection * kJumpForward, -kJumpSpeed}; | ||
| 90 | setState(FighterState::Air); | ||
| 91 | } | ||
| 92 | break; | ||
| 93 | case FighterState::Air: | ||
| 94 | velocity.y += kGravity * dt; // 重力:速度を変える(位置は下で速度から) / gravity changes the velocity (the | ||
| 95 | // position follows from the velocity below) | ||
| 96 | break; | ||
| 97 | case FighterState::Land: | ||
| 98 | if (stateTime >= kLandFrames) setState(FighterState::Idle); | ||
| 99 | break; | ||
| 100 | } | ||
| 101 | |||
| 102 | // 半陰的オイラー法:速度を先に、その速度で位置を / semi-implicit Euler: velocity first, then the position with it | ||
| 103 | position += velocity * dt; | ||
| 104 | |||
| 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; | ||
| 108 | velocity = {0.0f, 0.0f}; | ||
| 109 | setState(FighterState::Land); | ||
| 110 | } | ||
| 111 | chooseFrame(dt); | ||
| 112 | } | ||
| 113 | |||
| 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) { | ||
| 117 | switch (state) { | ||
| 118 | case FighterState::Idle: | ||
| 119 | animator.play(idleClip); | ||
| 120 | break; | ||
| 121 | case FighterState::Walk: | ||
| 122 | animator.play(walkingBack ? walkBackClip : walkClip); | ||
| 123 | break; | ||
| 124 | case FighterState::Crouch: | ||
| 125 | frame = stateTime < kCrouchInFrames ? fCrouchIn : fCrouch; | ||
| 126 | return; | ||
| 127 | case FighterState::JumpSquat: | ||
| 128 | case FighterState::Land: | ||
| 129 | frame = fCrouchIn; | ||
| 130 | return; | ||
| 131 | case FighterState::Air: | ||
| 132 | // 上昇中・頂点の近く・落下中 / rising, near the top, falling | ||
| 133 | frame = velocity.y < -180.0f ? fJumpUp : velocity.y < 180.0f ? fJumpTuck : fJumpDown; | ||
| 134 | return; | ||
| 135 | } | ||
| 136 | animator.update(dt); | ||
| 137 | frame = animator.frame(); | ||
| 138 | } | ||
| 139 | |||
| 140 | Rect Fighter::pushbox() const { | ||
| 141 | // 足元からの箱。空中は脚をたたむので下が空く(相手の上を越えられる) / boxes from the feet; in the air the legs are | ||
| 142 | // tucked, so the bottom is open (a fighter can pass over the other) | ||
| 143 | Rect local = state == FighterState::Crouch ? Rect{-15.0f, -60.0f, 30.0f, 60.0f} | ||
| 144 | : state == FighterState::Air ? Rect{-13.0f, -86.0f, 26.0f, 58.0f} | ||
| 145 | : Rect{-14.0f, -88.0f, 28.0f, 88.0f}; | ||
| 146 | return local.translated(position); | ||
| 147 | } | ||
| 148 | |||
| 149 | void Fighter::draw(SpriteBatch &batch, float alpha, float layer) const { | ||
| 150 | // 補間した位置を整数に丸める(ピクセルアートは整数の位置に) / the interpolated position, rounded to whole pixels | ||
| 151 | Vec2 p = lerp(previous, position, alpha); | ||
| 152 | Sprite s = sheet.sprite(frame, {std::round(p.x), std::round(p.y)}, kPivot); | ||
| 153 | s.flipX = facing < 0.0f; // 絵は右向き:左向きは左右反転 / the art faces right; facing left mirrors it | ||
| 154 | s.layer = layer; | ||
| 155 | batch.draw(s); | ||
| 156 | } | ||
ファイル: /dev/null | b/games/fighter/src/fighter.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,67 @@ | |||
| 1 | // ファイター:状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理(重力・速度・地面)、コマ送りのアニメーション | ||
| 2 | // A fighter: a state machine (idle, walk, crouch, jump), 2D physics (gravity, velocity, the ground) and frame | ||
| 3 | // animation | ||
| 4 | #pragma once | ||
| 5 | |||
| 6 | #include "controls.hh" | ||
| 7 | |||
| 8 | #include "engine/animation.hh" | ||
| 9 | #include "engine/rect.hh" | ||
| 10 | #include "engine/sprite_batch.hh" | ||
| 11 | #include "engine/sprite_sheet.hh" | ||
| 12 | |||
| 13 | #include <string> | ||
| 14 | |||
| 15 | // キャンバスは640×360(画面に2倍)。足元のy座標 / the canvas is 640 × 360 (×2 on screen). The y of the feet | ||
| 16 | constexpr float kGroundY = 320.0f; | ||
| 17 | |||
| 18 | // 状態。どの状態でも「何ステップ目か」(stateTime)を数える:格闘ゲームの時間はフレーム数 | ||
| 19 | // The states. Every state counts its steps (stateTime): in fighting games time is measured in frames | ||
| 20 | enum class FighterState { | ||
| 21 | Idle, // 立ち / standing | ||
| 22 | Walk, // 歩き(前・後ろ) / walking (forwards or backwards) | ||
| 23 | Crouch, // しゃがみ / crouching | ||
| 24 | JumpSquat, // 跳ぶ前のため(数フレーム、まだ地面) / the crouch before take-off (a few frames, still on the ground) | ||
| 25 | Air, // 空中(放物線、空中では向きも軌道も変えられない) / in the air (a parabola; neither facing nor arc can | ||
| 26 | // change) | ||
| 27 | Land, // 着地の硬さ(数フレーム動けない) / landing recovery (a few frames without control) | ||
| 28 | }; | ||
| 29 | const char *stateName(FighterState state); | ||
| 30 | |||
| 31 | class Fighter { | ||
| 32 | public: | ||
| 33 | Fighter(const SpriteSheet &sheet, std::string name, Vec2 start, float facing); | ||
| 34 | |||
| 35 | // 1ステップ(1/60秒)進める。opponentXで相手の方を向く / advances one step (1/60 s); faces the opponent at opponentX | ||
| 36 | void update(float dt, const Controls &controls, float opponentX); | ||
| 37 | // ステップの最初に呼ぶ:描くときの補間用に今の位置を覚える / call at the start of a step: remembers the position | ||
| 38 | // for interpolation when drawing | ||
| 39 | void savePrevious() { previous = position; } | ||
| 40 | |||
| 41 | // 押し合いの箱(ワールド座標):二人が重ならないための箱 / the push box (world): keeps the two fighters apart | ||
| 42 | Rect pushbox() const; | ||
| 43 | void draw(SpriteBatch &batch, float alpha, float layer) const; | ||
| 44 | // 前を押しているか(向きに対して) / is "forward" held (relative to the facing) | ||
| 45 | 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; } | ||
| 47 | |||
| 48 | std::string name; | ||
| 49 | Vec2 position; // 足元の中心(ワールドのピクセル、y下向き) / the feet center (world pixels, y down) | ||
| 50 | Vec2 previous; // 前のステップの位置 / last step's position | ||
| 51 | Vec2 velocity; // ピクセル毎秒 / pixels per second | ||
| 52 | float facing = 1.0f; // +1 = 右向き、-1 = 左向き / +1 = facing right, -1 = facing left | ||
| 53 | FighterState state = FighterState::Idle; | ||
| 54 | int stateTime = 0; // この状態で何ステップ目か / steps spent in this state | ||
| 55 | bool walkingBack = false; | ||
| 56 | int frame = 0; // 今のコマ(スプライトシートの番号) / the current frame (sprite-sheet index) | ||
| 57 | |||
| 58 | private: | ||
| 59 | void setState(FighterState next); | ||
| 60 | void chooseFrame(float dt); | ||
| 61 | |||
| 62 | const SpriteSheet &sheet; | ||
| 63 | const AnimationClip *idleClip, *walkClip, *walkBackClip; | ||
| 64 | Animator animator; | ||
| 65 | float jumpDirection = 0.0f; // -1 後ろ、0 垂直、+1 前 / -1 back, 0 straight up, +1 forwards | ||
| 66 | int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown; | ||
| 67 | }; | ||
ファイル: /dev/null | b/games/fighter/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,27 @@ | |||
| 1 | // 格闘ゲーム全体で一つの共有データ(mainが作り、シーンは参照で持つ) | ||
| 2 | // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "engine/camera2d.hh" | ||
| 6 | #include "engine/font.hh" | ||
| 7 | #include "engine/game_loop.hh" | ||
| 8 | #include "engine/input.hh" | ||
| 9 | #include "engine/sprite_batch.hh" | ||
| 10 | #include "engine/sprite_sheet.hh" | ||
| 11 | |||
| 12 | // 仮想解像度:640×360(1280×720に2倍)。ファイターが大きく描ける / the virtual resolution: 640 × 360 (×2 in | ||
| 13 | // 1280 × 720), so the fighters can be big | ||
| 14 | constexpr Vec2 kViewSize = {640.0f, 360.0f}; | ||
| 15 | |||
| 16 | struct Game { | ||
| 17 | Window &window; | ||
| 18 | Input &input; | ||
| 19 | GameLoop &loop; | ||
| 20 | SpriteBatch &batch; | ||
| 21 | const Font &ui; // mono16:1280×720のUI / the 1280 × 720 UI | ||
| 22 | const Font &pixel; // pixel12:キャンバスの中 / inside the canvas | ||
| 23 | const Font &tiny; // pixel5:デバッグ表示 / debug labels | ||
| 24 | const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) | ||
| 25 | Camera2D screen; // 1280×720のUI / the 1280 × 720 UI | ||
| 26 | bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels | ||
| 27 | }; | ||
ファイル: /dev/null | b/games/fighter/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,63 @@ | |||
| 1 | // 2D格闘ゲーム(第30〜32章) / The 2D fighting game (chapters 30-32) | ||
| 2 | // | ||
| 3 | // 第30章:ファイターの状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理、コマ送りのアニメーション、二人の入力 | ||
| 4 | // Chapter 30: the fighter state machine (idle, walk, crouch, jump), 2D physics, frame animation, two players' input | ||
| 5 | // | ||
| 6 | // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): | ||
| 7 | // 1P A D 前後・W ジャンプ・S しゃがみ / A D walk, W jump, S crouch | ||
| 8 | // 2P ← → 前後・↑ ジャンプ・↓ しゃがみ / arrow keys | ||
| 9 | // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック) / gamepads: 1st = 1P, 2nd = 2P (d-pad or left stick) | ||
| 10 | // F1 押し合いの箱と状態 / push boxes and states Esc 終了 / quit | ||
| 11 | #include "fight_scene.hh" | ||
| 12 | #include "game.hh" | ||
| 13 | |||
| 14 | #include "engine/pixel_canvas.hh" | ||
| 15 | #include "engine/window.hh" | ||
| 16 | |||
| 17 | #include <memory> | ||
| 18 | #include <optional> | ||
| 19 | |||
| 20 | int main() { | ||
| 21 | Window window; | ||
| 22 | if (!window.create(1280, 720, "OpenGL Tutorial - Fighter")) return 1; | ||
| 23 | |||
| 24 | std::optional<SpriteBatch> batch = SpriteBatch::create(); | ||
| 25 | std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); | ||
| 26 | std::optional<Font> pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest); | ||
| 27 | std::optional<Font> tiny = Font::load("assets/fonts/pixel5.fnt", TextureFilter::Nearest); | ||
| 28 | // 二人のファイター:同じ骨格・同じコマ割りで色だけ違う(パレットスワップ) / the two fighters: same skeleton and | ||
| 29 | // frame layout, different colors (a palette swap) | ||
| 30 | std::optional<SpriteSheet> hayate = SpriteSheet::loadAtlas("games/fighter/assets/hayate.atlas"); | ||
| 31 | std::optional<SpriteSheet> jin = SpriteSheet::loadAtlas("games/fighter/assets/jin.atlas"); | ||
| 32 | if (!batch || !ui || !pixel || !tiny || !hayate || !jin) return 1; | ||
| 33 | |||
| 34 | Input input; | ||
| 35 | input.attach(window); | ||
| 36 | bindPlayerActions(input); | ||
| 37 | |||
| 38 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | ||
| 39 | 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, | ||
| 41 | .tiny = *tiny, .fighters = {&*hayate, &*jin}, .screen = Camera2D::screen({1280.0f, 720.0f})}; | ||
| 42 | |||
| 43 | SceneManager scenes; | ||
| 44 | scenes.push(std::make_unique<FightScene>(game)); | ||
| 45 | |||
| 46 | loop.run( | ||
| 47 | window, input, | ||
| 48 | [&](float dt) { | ||
| 49 | scenes.update(dt); | ||
| 50 | if (scenes.empty()) window.close(); | ||
| 51 | }, | ||
| 52 | [&](float alpha) { | ||
| 53 | // 世界は640×360のキャンバスへ(2倍で画面に)、UIは1280×720で / the world into the 640 × 360 canvas (×2 on | ||
| 54 | // screen), the UI at 1280 × 720 | ||
| 55 | canvas.begin(hexColor(0x1b1726ff)); | ||
| 56 | scenes.draw(alpha); | ||
| 57 | canvas.present(window.width(), window.height()); | ||
| 58 | letterbox(window.width(), window.height(), game.screen.viewSize, false).apply(); | ||
| 59 | scenes.drawUi(alpha); | ||
| 60 | scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize); | ||
| 61 | }); | ||
| 62 | return 0; | ||
| 63 | } | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。