37. TPS パート2:3D衝突判定と物理
第36章の終わりで、兵士は歩き、走り、狙える様になりました。
カメラは既にレベルの事を知っていて、当たり判定の箱に球を飛ばし、壁が邪魔になると近づきました。
でも、兵士自身は知りません。
位置は単にposition + dt * velocityなので、壁も木箱も通り抜け、階段の上の空中も歩いて行きました。
此の章で兵士に体を与えます。
縦に立ったカプセルをレベルの箱に対して動かし、めり込んだら押し出し、壁に引っかからずに沿って滑り、地面に立ち、重力で落ち、ジャンプし、階段を上り下りします。
殆どは小さな幾何です。
クランプ、一番近い点、平方根が1つ、そして線型代数のシリーズの射影が1つです。
残りはゲームの手触りで、幾つかの定数と、ジャンプを公平に感じさせる2つの小さなタイマーです。
他のゲームの章と同じく、新しいOpenGLの関数はありません。
新しく描く物はデバッグ用の表示だけです。
37.1 此の章で作る物
走りながらのジャンプの途中で、脚を縮めた兵士です:
動画はアリーナの中を短く走ります。
階段を上って台に乗り、其の上を走り、西の縁から落ち(1.5 mの段差)、斜めに壁に向かって壁に沿って進み、ジャンプし、最後に上からのデバッグ表示で走った道の軌跡を見せます:
第36章の操作は其の儘で、新しいキーが3つあります:
- スペースでジャンプします。
- Lで壁ずりのオン・オフを切り替えます。壁に沿って滑るのと、壁でぴたっと止まるのを比べられます。
- Oでプレイヤーの真上の高い所から見下ろすカメラに切り替えます。遊ぶ為のカメラは裏で動き続けます。
- Bは体のカプセル(地面では黄色、空中では赤)と、最後の4秒の足元の軌跡も描く様になりました。
- F3には体の4行目が増えました:地面にいるか空中か、壁、段差を上った、下に吸い付いた、接触の数、高さ、速度、ジャンプの回数、壁ずりがオンか。
変わるのはgames/tps/の中のファイルだけです:
src/collision3d.hh、src/collision3d.cc:closestPoint、Contact、sphereAabb、Capsule、capsuleAabb、deepestContactsrc/character_body.hh、src/character_body.cc(新規):CharacterBody。動き、滑り、着地し、段差を上るカプセルsrc/play_scene.hh、src/play_scene.cc:プレイヤーはCharacterBodyになります。重力、コヨーテタイムと先行入力付きのジャンプ、空中制御、軌跡、上からの視点、F3の新しい行src/character.hh、src/character.cc:空中の脚の姿勢src/renderer.hh、src/renderer.cc:デバッグ用カプセルの為の球のメッシュsrc/main.cc:jumpのアクション。CMakeLists.txtとREADME.md
新しいソースファイルはゲームのCMakeLists.txtに入ります:
# 第36〜39章:三人称シューティング(TPS) / Chapters 36-39: the third-person shooter (TPS)
add_executable(tps
src/main.cc
src/collision3d.cc
src/character_body.cc
src/frustum.cc
src/level.cc
src/renderer.cc
src/character.cc
src/third_person_camera.cc
src/play_scene.cc)
target_include_directories(tps PRIVATE src)
target_link_libraries(tps PRIVATE engine)
enable_warnings(tps)
set_working_directory(tps)
そしてmainは他のアクションの隣で新しいアクションを結び付けます:
input.bind("jump", {InputBinding::key(GLFW_KEY_SPACE)});
37.2 体:縦に立ったカプセル
何故カプセルなのか
最初に決めるのは、物理の中でキャラクターの代わりになる形です。
其れはモデル其の物では決してありません。
ノードの階層の中で箱で出来た11個の部品が歩く度に揺れるのでは、判定が遅い上に、歩きの周期の各フレームで当たり方が変わってしまいます。
ゲームのキャラクターの体は、変わらない単純な形1つで、候補は普通3つです:
- 箱は第26章の2Dゲームで使った物で、箱で出来たレベルなら当然の選択です。3Dでは角が問題になります。何個もの箱で出来た壁に沿って歩くと、箱の体は箱と箱の間の小さな継ぎ目に引っかかります。段差に向かって歩くと、平らな底の縁が段の面に当たって止まります。そして箱がキャラクターと一緒に回るなら、壁の近くで向きを変えると角が壁にめり込みます。
- 球には其の問題は全く無いのですが、身長1.8 mの兵士に足りる高さの球は幅も1.8 mです。
- カプセルは、両端に半球の付いた円柱です。コードから見ると、線分(芯の線分)から半径以内にある全ての点です。縦に立てれば、キャラクターと同じ位細く、同じ位高く、角が無く、丸い底は小さな縁を乗り越え、どの方向から見ても同じなので、向きを変えても何も変わりません。
其の為、PhysX、Jolt、Unity、Unreal、Godotのキャラクターコントローラーはどれもカプセルを使い、あたし達も其うします。
あたし達のカプセルは縦だけです。
決して傾かないので、当たり判定がとても小さくなります。
数字
兵士のカプセルは半径0.35 m、高さ1.8 mです(モデルのヘルメットの天辺は1.91 mで、カプセルは其の少し下で終わります)。
baseは一番下の点で、足元です。
丁度第36章がキャラクターの原点を置いた所です。
芯の線分は足元から0.35 mから1.45 mまでで、下と上の半球の中心です。
// 縦に立ったカプセル(第37章のキャラクターの体):底の点base、半径radius、全体の高さheight(≥ 2·radius)。
// 中心の線分は base + (0, radius, 0) から base + (0, height − radius, 0) まで
// An upright capsule (the characters' body, chapter 37): bottom point base, radius, total height (≥ 2·radius). Its
// core segment runs from base + (0, radius, 0) to base + (0, height − radius, 0)
struct Capsule {
Vec3 base;
float radius = 0.35f;
float height = 1.8f;
float bottomY() const { return base.y + radius; } // 下の球の中心の高さ / height of the lower sphere's center
float topY() const { return base.y + height - radius; } // 上の球の中心の高さ / height of the upper sphere's center
Aabb bounds() const {
return {{base.x - radius, base.y, base.z - radius}, {base.x + radius, base.y + height, base.z + radius}};
}
};
bounds()はカプセル自身のAABBで、安い最初の判定に使います。
Aabb::loとhiと同じく、名前はWindowsでマクロになっているmin、max、near、farを避けています。
37.3 カプセルと箱
考え方
必要な判定は1つの質問に答えます。
カプセルが箱にめり込んだら、外に出るには何方へどれだけ動けば良いか?
其の組、向きと深さが接触(コンタクト)です:
// めり込み:normalの向きにdepthだけ動かすと離れる(normalは箱から外向きの単位ベクトル) / a penetration: moving by depth
// along normal separates them (normal = unit vector pointing out of the box)
struct Contact {
Vec3 normal;
float depth = 0.0f;
int index = -1;
};
球なら簡単です。
第26章の最小移動ベクトルと同じ考えで、軸ごとではなく距離で測るだけです。
箱の中で球の中心に一番近い点を探します。
其の点が半径より近ければ球は箱と重なっていて、其の点から中心への向きが出口で、半径に足りない分が深さです。
カプセルは芯の線分に沿って動かした球なので、線分と箱の一番近い2点で同じ事が出来ます。
一般には面倒な判定です。
でも、あたし達の線分は縦なので、2回のクランプになります:
- 線分の中で箱に一番近い高さを探します。箱の真ん中の高さを線分にクランプします:。其れで点が決まります。
- 後はにある球と箱の問題です: = 箱の中でに一番近い点、、なら法線は、深さはです。
何故1番目の手順で正しいのでしょう?
線分が縦なので、線分の上のどの高さでも、線分と箱の水平の距離は同じです。
変わるのは縦の隙間だけです。
線分の高さの範囲と箱の高さの範囲が重なっていれば、一番良いは重なりの中のどの高さでも良く(縦の隙間が0になります)、クランプした真ん中は其の1つです(真ん中は箱の範囲の中にあり、線分の範囲へクランプすると、箱の範囲から出ずに重なりの方へ動くからです)。
重なっていなければ、クランプは線分の端のうち箱に近い方を返し、其れも一番良いです。
従って、縦のカプセルなら、クランプは線分の本当の一番近い点を与え、判定は正確です。
計算例
真ん中の図を使います。
カプセルは足元がに立ち、段の箱はからまで、高さはまでです。
箱の真ん中の高さはで線分より下なので、クランプでbottomY まで上がります:。
箱の中でに一番近い点は、各座標を箱の中にクランプした物です。
はからへ、はからへ下がり、はの儘なので、、段の角です。
丸い底が段の面ではなく角に触れているので、法線は角から離れる様に上と後ろを向いています。
此の傾いた法線は2回大事になります。
何が地面かを決める時(37.6)と、段差を上る時(37.7)です。
(ベクトルを其の長さで割る正規化は線型代数のシリーズの第3章です。)
コード
箱の一番近い点は軸ごとのクランプです:
Vec3 closestPoint(const Aabb &box, Vec3 p) {
return {std::clamp(p.x, box.lo.x, box.hi.x), std::clamp(p.y, box.lo.y, box.hi.y), std::clamp(p.z, box.lo.z, box.hi.z)};
}
球の判定は上の手順通りで、場合が1つ増えています:
std::optional<Contact> sphereAabb(Vec3 centre, float radius, const Aabb &box) {
Vec3 q = closestPoint(box, centre);
Vec3 d = centre - q;
float dist2 = dot(d, d);
if (dist2 >= radius * radius) return std::nullopt;
if (dist2 > 1e-12f) {
float dist = std::sqrt(dist2);
return Contact{d / dist, radius - dist, -1};
}
// 中心が箱の中:一番近い面から外へ / the center is inside the box: out through the nearest face
const float gaps[6] = {centre.x - box.lo.x, box.hi.x - centre.x, centre.y - box.lo.y,
box.hi.y - centre.y, centre.z - box.lo.z, box.hi.z - centre.z};
const Vec3 normals[6] = {{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}};
int best = 0;
for (int i = 1; i < 6; ++i)
if (gaps[i] < gaps[best]) best = i;
return Contact{normals[best], gaps[best] + radius, -1};
}
先に距離の2乗で比べるので、一番多い「接触なし」の答えには平方根が要りません。
増えた場合は、中心が箱の中にある時です。
其の時はで、は0になり、向きがありません。
コードは箱の一番近い面を使います。
第26章のMTVが浅い方の軸を選ぶのと同じで、深さは其の面までの隙間に半径を足した物です。
37.4で見る様に、速い動きを危なくするのは此の場合です。
一番近い面は、入って来た面とは限りません。
カプセルの判定は2回のクランプで、deepestContactは全ての箱に対して其れを行い、一番深い接触を残します:
std::optional<Contact> capsuleAabb(const Capsule &capsule, const Aabb &box) {
float y = std::clamp(0.5f * (box.lo.y + box.hi.y), capsule.bottomY(), capsule.topY());
return sphereAabb({capsule.base.x, y, capsule.base.z}, capsule.radius, box);
}
std::optional<Contact> deepestContact(const Capsule &capsule, std::span<const Aabb> boxes) {
std::optional<Contact> best;
Aabb reach = capsule.bounds();
for (size_t i = 0; i < boxes.size(); ++i) {
if (!overlaps(reach, boxes[i])) continue; // 大まかな判定(ブロードフェーズ) / the coarse test (broad phase)
std::optional<Contact> c = capsuleAabb(capsule, boxes[i]);
if (c && (!best || c->depth > best->depth)) {
best = c;
best->index = static_cast<int>(i);
}
}
return best;
}
アリーナには当たり判定の箱が85個あり、其の殆どは遠くにあります。
カプセルのboundsとoverlaps(reach, box)(第36章の厳密なAABBの判定)がブロードフェーズです。
正確な判定の前に、幾つかの比較で、絶対に触れない箱を全て捨てます。
85個なら全部を回るループで十分です。
何千個もあるレベルなら、先に格子や木に入れます(37.11)。
37.4 動いてから押し出す
体
CharacterBodyは位置、速度、最後の移動の結果を持ちます:
class CharacterBody {
public:
Vec3 position; // 足元(カプセルの底) / the feet (the bottom of the capsule)
Vec3 velocity; // m/s。重力は呼ぶ側が足す / m/s. The caller adds gravity
float radius = 0.35f;
float height = 1.8f;
float stepHeight = 0.3f; // これ以下の段差は自動で上る / ledges up to this height are climbed automatically
float groundNormalY = 0.7f; // n.yがこれより大きい面は地面(約45°まで) / n.y above this = ground (up to ~45°)
bool slide = true; // false:壁に当たると止まる(比べるため、L) / false: stop at walls (to compare, L)
// 最後のmoveの結果 / results of the last move
bool grounded = false;
bool hitWall = false;
bool steppedUp = false;
bool snappedDown = false;
int contacts = 0; // 押し出した回数 / how many times it was pushed out
Capsule capsule() const { return {position, radius, height}; }
// 1ステップ動かす。canStep = 段差を上る・下りるか(空中ではfalseで良い) / one step. canStep = climb / snap
// ledges (may be false in the air)
void move(float dt, std::span<const Aabb> solids, bool canStep = true);
// その位置に置いたらめり込むか / would the body penetrate something at this position?
bool blockedAt(Vec3 feet, std::span<const Aabb> solids) const;
呼ぶ側が速度を決め(重力、ジャンプ、プレイヤーの入力、37.6)、固定ステップごとに1回moveを呼びます。
moveがする事は2つです。
速度で位置を進める事と、其れで出来ためり込みを直す事です。
押し出す
直すのはresolveです:
void CharacterBody::resolve(std::span<const Aabb> solids) {
// 一番深い接触から順に押し出す(角では2〜3枚に同時に当たる) / push out of the deepest contact first (in a corner
// it touches two or three boxes at once)
for (int iteration = 0; iteration < 4; ++iteration) {
std::optional<Contact> c = deepestContact(capsule(), solids);
if (!c) break;
++contacts;
if (stepping && c->normal.y <= groundNormalY && climb(solids[static_cast<size_t>(c->index)])) continue;
position = position + (c->depth + 1e-4f) * c->normal;
bool ground = c->normal.y > groundNormalY;
if (ground) grounded = true;
else if (c->normal.y > -groundNormalY) hitWall = true; // 天井はどちらでもない / a ceiling is neither
一番深い接触を聞き、其の法線の向きに深さ(と0.1 mm、深さ0で同じ接触がまた見つからない様に)だけ体を外へ動かし、もう一度聞きます。
最大4回です。
角ではカプセルは2枚の壁と床に同時に触れていて、押し出し1回で1つずつ直ります。
一番深い物からというのが大事です。
一番深い接触が一番間違っていて、先に其れを直すと、浅い方も一緒に直る事がよくあります(1枚の壁から押し出すと、軽く触れていた箱の角から体が離れる、等)。
4回の後に残った物は次のステップで直ります。
接触の法線は、体が何に触れたかも教えてくれます。
十分に上を向いた法線は地面、十分に下を向いた法線は天井、其の間は全て壁です。
0.7については37.6で説明します。
climbの行は37.7の段差の決まりなので、今は無視して下さい。
何故スイープしないのか
此のやり方を離散的な衝突判定と言います。
先に動き、其れから重なりを探して直します。
もう1つのやり方はスイープ(連続的な衝突判定とも言います)です。
動く前に、動きの中で最初に何かに触れるのは何時かを計算し、丁度其処まで動き、残りを滑らせます。
第26章には両方ありました。
衝突の正確な時刻を出すsweepと、動いてから1軸ずつ押し戻すmoveAndSlideです。
キャラクターには押し出しの方が良い既定の選択です。
理由は3つです:
- 何でも直せる。スイープは体が正しい場所から始まる事を前提にしています。少しでも箱の中から始まると(出現した直後、テレポートの後、動く床にめり込まれた時、丸め誤差)、衝突の時刻は0になり、体は動けなくなります。押し出しは、重なりがどう出来たかを気にしません。
- 判定が簡単。縦のカプセルと箱の重なりは上の2回のクランプです。スイープするカプセルには、カプセルの分だけ大きくした箱に対するレイが要り、其れは辺と角が丸い箱です。面、12個の円柱の一部、8個の球の一部です。第36章の
sphereCastは箱を角の尖った儘大きくしてごまかしていて、辺の近くでは少し手前で止まります。カメラには安全ですが、体なら通り過ぎる角全てに引っかかります。 - 複数の接触が自然に扱える。角、壁、床が同時でも、同じループを何回か回るだけです。
3Dでは押し出しの向きはどの向きでも良いので、第26章のxとyを別々に動かす技は要りません。
斜めの壁も、箱の辺も、角も、接触の法線が1つの決まりで扱います。
先に動く代わりに払う物は、第26章が注意したトンネリング(すり抜け)です。
すり抜けを防ぐサブステップ
押し出しが上手く行くのは、球の中心(点)が箱の中に入らない限りです。
外にある間は、一番近い点は来た側にあり、法線は体を押し戻します。
中に入ってしまうと、コードは一番近い面を使います。
中心が薄い箱の真ん中を越えていれば、一番近い面は向こう側の面で、体は箱を通り抜けて押し出されます。
直し方は、一度に遠くまで動かない事です:
void CharacterBody::advance(float dt, std::span<const Aabb> solids) {
// 一度に半径の半分より進まない:速くても薄い箱をすり抜けない(トンネリング) / never move more than half the
// radius at once, so fast motion does not tunnel through thin boxes
float distance = length(velocity) * dt;
int pieces = std::max(1, static_cast<int>(std::ceil(distance / (0.5f * radius))));
float h = dt / static_cast<float>(pieces);
for (int i = 0; i < pieces; ++i) {
position = position + h * velocity;
resolve(solids);
}
}
動きを最大 mの部分に分け、其の度にresolveを動かします。
各部分の始まりでは体は精々触れているだけ(前のresolveが其うしたから)なので、より短く動けば中心はまだ箱の外です。
半径の半分にしたのは、少しめり込んだ状態から始まる部分の為の余裕です。
例えば、重力が毎ステップ床に引き込む数ミリです。
此れで動きが分かれるのはどれ位の頻度でしょう?
1秒に60回の更新で、1回0.175 mは10.5 m/sです。
歩き(3.2 m/s、1回5.3 cm)、走り(6 m/s、10 cm)、台からの着地(1.5 m落ちると m/s)は全て1回のままです。
もっと速くなるのは長い落下だけです。
ゲームは落ちる速さを30 m/sに抑えていて、1回0.5 m、0.167 mずつ3回になります。
つまりサブステップは毎日の仕事ではなく保険で、其れで良いのです。
要らない時には何も掛かりません。
サブステップが無いと、30 m/sの落下は箱を抜けるでしょうか?
1回の動きで中心が厚さの箱の真ん中を越えるのは、其の動きがより長い時だけです。
アリーナの床(床のタイル自体は当たり判定を持たず、厚さ1 mの見えない箱が床です)では0.85 mで、どの動きよりも長いです。
レベルのファイルのコメントにある通り、わざと厚くしてあります。
床が0.05 mなら mで足り、0.5 mの動きは4回に1回其れを越えます。
衝突の直前の更新で中心が触れる位置より上にいられる幅は0.5 mで、其のうち m、4分の1の時に越えるからです。
課題3で試します。
37.5 壁に沿って滑る
射影
押し出しで体が壁から出ても、直るのは位置だけで、速度はまだ壁の方を向いています。
速度は次のステップに持ち越される状態です。
体は毎ステップ同じだけめり込み直して押し戻され、溜まった速度は壁が終わった所で出て来るので、角を過ぎると体は横へ飛び出します。
一番分かり易いのは重力です。
着地で下向きの速度が消えなければ、兵士が床に立っている間も其れは増え続け、毎回の更新で床により深く押し込まれ、足場から歩き出た瞬間に30 m/sで落ちる事になります。
欲しいのは、面に向かう部分を除いた速度です。
其れは線型代数のシリーズの第4章の壁ずり移動です。
面の単位法線を使って、
は法線の向きにどれだけ速く動いているかで、面の中へ向かっている時は負です。
は其の部分をベクトルにした物(のへの射影)で、其れを引くと面に平行な部分が残ります。
此れがresolveのループの残りです:
float into = dot(velocity, c->normal);
if (into >= 0.0f) continue; // もう離れていく / already moving away
if (slide || ground) {
// 壁ずり:面に向かう成分だけを消す。残りは面に沿う速度 / wall slide: remove only the part towards the
// surface; what remains runs along it
velocity = velocity - into * c->normal;
} else {
// 比べる用:壁に当たったら水平に止まる(ゲームでは引っかかって動けなくなる) / for comparison: stop horizontally
// at a wall (in a game you get stuck on every corner)
velocity = {0.0f, std::fmin(velocity.y, 0.0f), 0.0f};
}
}
}
滑らせるのはinto < 0の時、体が面の中へ向かっている時だけです。
線型代数の章で書いた通り、既に離れていく体は速度を其の儘にします。
計算例
下のスクリーンショットでは、兵士は6 m/sで北から右へ45°の斜めに走り、台の東にある内側の壁の1枚に当たります。
其の面は西を向いていて、です(北は):
東向きの部分が消え、兵士は壁に沿って北へ4.24 m/s、自分の速さので走ります。
一般には、壁の法線から角度で壁に当たるとが残ります。
真正面()なら何も残らず、かすめるだけなら殆ど何も失いません。
プレイヤーはWを押し続けているので、次のステップの入力が速度を少し壁の方へ戻し、壁ずりがまた其の部分を消します。
壁に沿った速さは、目標の速度の壁に沿った部分に留まります。
ゲームの更新のループをシミュレーションすると4.243 m/s、丁度になります。
滑る場合と滑らない場合(L)
slide = falseは比べる為にあります。
壁に触れる度に水平の動きを止める物で、素朴な「ぶつかったら止まる」の結果です。
右の軌跡は完全には止まっていません。
其の理由は理解しておく価値があります。
毎ステップ、入力が止まった体をまた目標の速度のまで加速し(37.6)、体はまた壁に触れる前に其れだけ動きます。
押し出しが消すのは法線の向きの部分だけなので、壁に沿った部分は残り、体は m/s、滑る時の5分の1の速さで北へじりじり進みます。
もっと急な角度の壁や角では、完全に動けなくなります。
其の為、どのキャラクターコントローラーも滑らせるのです。
着地も同じ式です。
床に対してはで、床へ向かう部分を消すと縦の速度が0になり、水平の速度は残ります。
落下が終わり、走りは続きます。
壁ずりがオフでも地面には射影を使います(slide || ground)。
其うしないと、Lでは着地の度に体が止まってしまいます。
天井()に対しては上向きの速度が消え、頭をぶつけたジャンプは其処で終わります。
37.6 地面・重力・ジャンプ
何を地面とするか
resolveは接触の法線がの時にgroundedを立てます。
は法線と真上の間の角度のコサイン(との内積、又も線型代数の第4章)なので、此の決まりは傾きが次より小さい面を全て地面とします
あたし達のレベルには坂がありません。
どの箱のどの面も平らか垂直です。
でも、37.3の計算例の様に、カプセルの丸い底は箱の辺で傾いた法線を作ります。
兵士が木箱の縁を越えて歩くと、球の中心が縁を過ぎるにつれて接触の法線はどんどん傾きます。
中心が縁を越えても、其の先 m未満の間は、まだ地面です。
其れより外では法線は45.57°より急で壁になり、傾いた法線に沿った押し出しが、ボールの様に体を縁から転がり落とします。
別の地面の判定は要りません。
重力が毎ステップ体を数ミリ床に引き込み、床が押し戻すので、地面にいる事は押し出しのおまけで分かります。
重力、ジャンプ、空中制御
PlaySceneは次の定数で体を動かします:
constexpr float kWalkSpeed = 3.2f; // m/s
constexpr float kRunSpeed = 6.0f; // m/s(Shift)
constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target
constexpr float kAirControl = 2.5f; // 空中ではゆっくりしか向きを変えられない / in the air it steers only slowly
constexpr float kGravity = 20.0f; // m/s²(現実の約2倍:ゲームでは重めが気持ち良い) / m/s² (about twice the real
// value: games feel better heavier)
constexpr float kJumpSpeed = 7.0f; // m/s → 高さ1.17 m(60 Hzの固定ステップ。v²/2gなら1.23 m) / m/s → 1.17 m high
// with the 60 Hz fixed step (v²/2g would give 1.23 m)
constexpr float kCoyoteTime = 0.1f; // 足場を離れてからまだ跳べる時間 / time after leaving a ledge that still allows a jump
constexpr float kJumpBuffer = 0.1f; // 着地の少し前に押したジャンプを覚えておく時間 / a jump pressed just before
// landing is remembered this long
水平の速度は、第36章のカメラに対する目標へ、指数的な平滑化で近づきます。
地面では毎秒12、空中では毎秒2.5です:
// 水平の速度だけを目標へ(上下は重力とジャンプ)。空中ではゆっくり / only the horizontal velocity approaches the
// target (vertical = gravity and jumps); slowly in the air
Vec3 &v = body.velocity;
float k = approach(body.grounded ? kAcceleration : kAirControl, dt);
v.x += k * (target.x - v.x);
v.z += k * (target.z - v.z);
此れが空中制御です。
本物の人間は空中では全く向きを変えられませんが、ゲームは少しだけ許します。
ジャンプを直せる位で、向きを反対にする程ではありません。
1回の更新で、目標までの差のうち地面では、空中ではが縮まります。
次は重力とジャンプです:
// 3. 重力とジャンプ。コヨーテタイム(足場を離れた直後)とジャンプの先行入力(着地の直前)で、押したのに
// 跳べないことをなくす
// 3. gravity and jumping. Coyote time (just after leaving a ledge) and a jump buffer (just before landing) make sure
// a press is never lost
coyote = body.grounded ? kCoyoteTime : coyote - dt;
jumpBuffer = in.actionPressed("jump") ? kJumpBuffer : jumpBuffer - dt;
bool jumped = false;
if (jumpBuffer > 0.0f && coyote > 0.0f) {
v.y = kJumpSpeed;
jumpBuffer = coyote = 0.0f;
jumped = true;
++jumps;
}
v.y -= kGravity * dt;
v.y = std::fmax(v.y, -30.0f); // 終端速度 / terminal velocity
重力は20 m/s²で、現実の9.81の約2倍です。
ゲームでは普通の選択です。
現実の重力では、役に立つ高さのジャンプは時間が掛かり過ぎて、浮いている様に感じます。
ジャンプの速さと重力から、昔からの公式で高さと滞空時間が出ます:
コードのコメントの括弧の中の1.23 mは此れです。
ゲームの中のジャンプは其れより少し低く、コメントが先に書いている1.17 mになります。
踏み切りのステップでジャンプの速さの儘動いた第30章の格闘家と違い、あたし達の更新は体が動く前に重力を引きます。
踏み切りのステップでもです。
従って体はステップで m/sで上ります(ステップ21は丁度0です):
此れはで、ステップが固定なのでどの機械でも同じです。
1.167 mは1 mの木箱と1.1 mの遮蔽には足り、1.5 mの台には足りません。
上る道は階段です。
更新のループのシミュレーションで、其れらの高さの箱に向かって歩きと走りの速さでジャンプさせて確かめました。
タイミングが合えば1 mと1.1 mの箱の上に着地し、1.5 mの箱には一度も乗れません。
終端速度の30 m/sに達するのは22.5 m()落ちた後で、アリーナには其んな高さはありません。
此れはレベルの外へ落ちた体が、床の20 m下で出発点に戻される前に、馬鹿げた速さにならない為の物です。
コヨーテタイムとジャンプの先行入力
2つの小さなタイマーがジャンプを甘くします。
- コヨーテタイム(崖から走り出て、気付いた時に初めて落ちるアニメのコヨーテが名前の由来):
coyoteは地面にいるステップごとに0.1秒に戻り、空中では減っていきます。正の間はジャンプ出来るので、足場から歩き出た少し後にスペースを押してもまだ跳べます。プレイヤーは自分の感覚で「縁で」押すので、コヨーテタイムが無いと2フレーム遅れた押下は無視され、ボタンが壊れている様に感じます。 - ジャンプの先行入力:押すと
jumpBufferが0.1秒になり、減っていきます。正の間は、体が地面に着いた途端にジャンプします。着地の少し前の押下は失われず、着地で効きます。
ジャンプはどちらも0にするので、1回押せば1回跳びます。
Celesteの様なプラットフォーマーは此れらの技で有名で、ジャンプのあるシューティングでも使われます。
ステップの残りが体を動かします:
body.move(dt, g.level.solids, !jumped);
if (body.position.y < -20.0f) { // 落ちたら出発点へ / fell out of the level: back to the start
// 補間もカメラも出発点から(下から飛んで来ない) / interpolation and camera restart there too (no swoop from below)
body.position = position = prevPosition = g.level.spawn;
v = {0.0f, 0.0f, 0.0f};
camera.reset(cameraPivot(), g.level.solids);
prevEye = camera.eye();
prevForward = camera.forward();
}
position = body.position;
Vec3 velocity = body.velocity; // 実際に動いた速度(壁ずりの後) / the velocity after sliding
ジャンプしたステップではcanStepがfalseなので、37.7の段差の決まりが、離れようとしている地面に体を吸い戻す事はありません。
positionは描画とカメラの為の写しで、第36章と同じくprevPositionと補間します。
歩きの周期が読むのは、壁ずりの後の速度です。
レベルの外へ落ちた体は、prevPositionとカメラと一緒に出発点へ戻します(enterと同じcamera.reset)。
其うしないと次のフレームは床の20 m下から補間され、ピボットの高さを毎秒8でしか追わないカメラは其処から舞い上がって来ます。
空中の姿勢
空中で脚が歩き続けるのはおかしいです。
姿勢は0から1の値airを持ち、其れが毎秒12で体の状態を追います:
// 空中の姿勢へなめらかに(着地で戻る) / blend into the airborne pose (and back on landing)
pose.air += ((body.grounded ? 0.0f : 1.0f) - pose.air) * approach(12.0f, dt);
if (!body.grounded) pose.walkAmount *= 1.0f - pose.air;
そしてapplyPoseは歩く脚と、決まった縮めた姿勢を混ぜます:
// 空中(第37章):左の太ももを前へ、右を後ろへ、両膝を曲げる。地面の姿勢とairで混ぜる
// Airborne (chapter 37): left thigh forward, right thigh back, both knees bent; mixed with the ground pose by `air`
const float airThigh[2] = {-0.55f, 0.25f}, airKnee[2] = {0.9f, 0.6f};
for (int s = 0; s < 2; ++s) {
float sign = s == 0 ? 1.0f : -1.0f; // 左右は逆位相 / left and right are in opposite phase
float thigh = -sign * swing * (1.0f - pose.air) + airThigh[s] * pose.air;
node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(thigh);
float forwardSwing = std::fmax(0.0f, sign * std::cos(phase)); // この脚が前へ動いている / this leg moves forward
float knee = w * pose.stride * (0.12f + 1.0f * forwardSwing) * (1.0f - pose.air) + airKnee[s] * pose.air;
node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(knee);
}
第36章と同じ手続き的なアニメーションで、パラメーターが1つ増えただけです。
左の太ももを前へ、右を後ろへ振り(−0.55と0.25ラジアン)、両膝を曲げます(0.9と0.6ラジアン)。
切り替えずに割合で混ぜるので、踏み切りと着地がなめらかになります。
空中で0.1秒経つとairはです。
カメラには何も新しい物は要りません。
第36章で既に、ピボットを縦には毎秒8の割合で追う様にしたので、ジャンプや階段では視点がガクッとせずになめらかに上がります。
37.7 階段:角に持ち上げ、下に吸い付く
箱で出来た階段
箱だけの当たり判定では坂を表せないので、階段は1段ごとに1個、6個の箱で当たります。
其々0.25 m高く、0.5 m短くなります(レベルのファイルのboxの行、階段のモデルの座標):
box stairs -1 0 -1.5 1 0.25 1.5
box stairs -1 0 -1.5 1 0.5 1
box stairs -1 0 -1.5 1 0.75 0.5
box stairs -1 0 -1.5 1 1 0
box stairs -1 0 -1.5 1 1.25 -0.5
box stairs -1 0 -1.5 1 1.5 -1
1段目に向かって歩くと、下の球は角に、上へしか傾いていない法線で触れます。
37.3の計算例程深くめり込んでもで、0.7の決まりでは壁です。
其の法線に沿って押し出すと、体は後ろへ押され、上へは少ししか上がらず、壁ずりが前への速さの殆どを消します。
丸い底は低い縁なら自分で乗り越えます(段差の決まりを外した試験では、カプセルは0.15 mの段を歩いて越えました)が、0.25 mではぴたっと止まります。
角の上に持ち上げる
其処で体に決まりを1つ足します。
下の球が低い箱の角に触れたら、押し戻す代わりに、球が角の上に乗るまで体を真上に持ち上げます。
bool CharacterBody::climb(const Aabb &box) {
// 下の球が低い箱の角に当たった(箱の上面が足元からstepHeight以内で、下の球の中心より下):横に押し返す代わりに、
// 球がその角に乗る高さまで真上に持ち上げる。近づくほど持ち上がるので、段差は小さな坂のように上れる
// The lower sphere touches the edge of a low box (its top within stepHeight of the feet and below the lower
// sphere's center): instead of pushing back sideways, lift straight up until the sphere rests on that edge. The
// closer it gets, the higher it is lifted, so a step is climbed like a small ramp
float rise = box.hi.y - position.y;
if (rise <= 0.0f || rise > stepHeight || box.hi.y > position.y + radius) return false;
Vec3 centre = position + Vec3{0.0f, radius, 0.0f};
Vec3 q = closestPoint(box, centre);
Vec3 toEdge = {q.x - centre.x, 0.0f, q.z - centre.z};
float flat = length(toEdge);
// 向かっている段だけ:離れていく段(下りるときの今の段)の角に乗せ直すと、体が角に引っかかって浮く
// Only a step we are moving towards: lifting the body back onto the edge of a step it is leaving (going down)
// would leave it hanging on that edge
if (flat >= radius || dot(toEdge, velocity) <= 0.0f) return false;
float lift = box.hi.y + std::sqrt(radius * radius - flat * flat) - centre.y + 1e-4f;
if (lift <= 0.0f || blockedAt(position + Vec3{0.0f, lift, 0.0f}, {&box, 1})) return false;
position.y += lift;
velocity.y = std::fmax(velocity.y, 0.0f);
grounded = steppedUp = true;
return true;
}
箱が十分低いのは、上面が足元からstepHeight(0.3 m)以内で、下の球の中心より下にある時です。
(既定の数字では2つ目の判定は何も決めません。0.3 mは半径0.35 mより小さいからです。stepHeightを半径より大きくすると意味を持ちます。)
半径の球が高さtopの角に、中心から水平に離れて乗るには、中心はになければなりません(ピタゴラスの定理)。
従って持ち上げる量は
で、は今の中心の高さです。
0.25 mの段を追ってみましょう。
球の中心は床から0.35 m、段の上面より0.1 m上なので、最初に角に触れるのは水平距離 mの所で、其処での持ち上げはです。
mでは m、中心が角の真上()なら0.25 m全部です。
近づく程高く持ち上がります。
中心は角の周りの円を描くので、段は小さな曲がった坂の様に振る舞い、歩く速さなら其の0.335 mを10分の1秒程で越えます。
中心が段の上に来れば、接触の法線は殆ど真上を向き、段は地面になり、普通の押し出しが引き継ぎます。
安全の為の確認もあります。
持ち上げる量は正でなければならず、持ち上げた体が段の箱自体と重なってはいけません(見た目より高い段や、狭すぎる隙間)。
velocity.yは0以上にクランプするので、少し落ちていた体が其れを次のステップへ持ち越す事はありません。
そしてsteppingは、移動の始めに体が地面にいて、呼ぶ側が許した時だけtrueです。
ジャンプ中や落下中の体は縁の上に持ち上げられず、着地しなければなりません。
更に、体は其の縁に向かって動いていなければなりません(dot(toEdge, velocity) > 0)。
下りで離れていく段の様に、遠ざかっている縁には決して上りません。
其うしないと、此の決まりが毎回の更新で体を其の縁に乗せ直し、其処で止まった兵士は縁に支えられて段の横の空中に浮いた儘になります。
上る決まりは、既に地面である接触も無視します(resolveのc->normal.y <= groundNormalY)。
其うしないと、重力が足元を数ミリ沈める床其の物が、毎回の更新で「数ミリの段差」になってしまいます。
走って上ると副作用が見えます。
6 m/sでは、角の傾いた法線に沿った押し出しが前への速さの一部を上への速さに変え、体は段から段へ跳ねるので、上っている間F3が時々「airborne」になります。
ゲームの中では自然に見えますし、壁ずりの式が傾いた法線でも壁と全く同じ様に働く良い例です。
下に吸い付く
下りは反対の問題です。
3.2 m/sで段から歩き出ると、体は一瞬空中にいます。
重力が0.25 m落とすのに秒掛かり、其の間に前へ更に0.5 m、丁度1段分進みます。
体は階段を跳ねながら下り、姿勢は1段ごとに空中に切り替わり、コヨーテタイムは其の一部を隠しても全部は隠せません。
其処でmoveの最後で下に吸い付けます:
void CharacterBody::move(float dt, std::span<const Aabb> solids, bool canStep) {
bool wasGrounded = grounded;
grounded = hitWall = steppedUp = snappedDown = false;
contacts = 0;
stepping = canStep && wasGrounded; // 段差を上ってよいのは地面にいたときだけ / climb ledges only from the ground
advance(dt, solids);
// 下りの段差に吸い付く:さっきまで地面にいて、跳んでいないなら、stepHeightまで下に地面を探す。一度に下ろすと
// 今の段の角に深くめり込み、角の斜めの法線で前へ押し出される(跳ねる、届かない)ので、5 cmずつ下ろして
// 地面に着いた所で止める
// Stick to the ground going down a step: if it was grounded a moment ago and did not jump, look for ground up to
// stepHeight below. Dropping it all at once would sink deep into the edge of the step it is leaving, and the edge's
// tilted normal would push it forward (a hop, or a miss), so lower it 5 cm at a time and stop on the first ground
if (canStep && wasGrounded && !grounded && velocity.y <= 0.0f) {
State before = save();
const int pieces = 6; // 0.3 m / 6 = 5 cm
for (int i = 0; i < pieces && !grounded; ++i) {
position.y -= stepHeight / static_cast<float>(pieces);
resolve(solids);
}
if (grounded) {
snappedDown = true;
velocity.y = 0.0f;
} else {
restore(before);
}
}
}
移動の前に地面にいて、今はいなくて、上へ動いていない(ジャンプしていない)なら、stepHeightまで5 cmずつ(6回に分けて)下ろし、其の度にresolveし、地面に着いた所でループを止めます。
何処かで地面に着けば其処に残り、何処でも着かなければ(1.5 mの台から歩き出た時)、F3に出るcontactsの数も含めて全てを元に戻し、普通に落ちます。
何故分けるのでしょう?
最初の版は0.3 mを一度に落としていました。
体が地面を失う時、球の中心は離れようとしている段の角を過ぎたばかりなので、0.3 m落とした球は其の段の角に深くめり込み、一番深い接触は下の段ではなく其の角になります。
すると押し出しは角の傾いた法線に沿って体を前と上へ動かします。
下の段の、本来より0.2 m程前に着地し(1回の更新で更新4回分の歩き)、時々は下の段に届かずに吸い付きが取り消されていました。
体のコードとアリーナの6個の階段の箱で、台から3.2 m/sで歩いて下る試験では、6段のうち4段は此の跳びと共に吸い付き、2段は7回と8回の更新(約0.12秒)の短い落下でした。
5 cmずつ下ろすと、球は角に少ししかめり込まないので、ボールの様に角を転がって越え、下りる途中で下の段を見つけます。
同じ試験で、今は体が下まで地面から離れず、1段ごとに約4回の更新で吸い付き、1回の更新の一番大きな動きは0.28 mではなく0.09〜0.14 mです(歩くだけなら0.053 m)。
残った小さな前への押しは、最後の1回がまだ触れている角の傾いた法線から来ます。
本物のエンジンは代わりに下向きのスイープで床を探します(37.11)。
其れなら床までの距離が直接分かります。
37.8 物理を見る
物理のバグは普通の画面では見え難いので、此の章ではデバッグの道具を3つ足します。
Bは当たり判定の箱の隣にカプセルを描きます。
エンジンには球のメッシュはありますがカプセルのメッシュは無いので、デバッグのカプセルはカプセルの大きさに伸ばした球、楕円体です。
線で描き、体が何処にいて地面にいるかを見せれば十分です:
// プレイヤーのカプセル(伸ばした球で近似して線で) / the player's capsule (approximated by a stretched sphere, as lines)
Vec3 feet = lerp(prevPosition, position, drawAlpha);
s.set("uColor", body.grounded ? Vec3{1.5f, 1.5f, 0.2f} : Vec3{2.0f, 0.4f, 0.1f});
s.set("uModel", translate(feet + Vec3{0.0f, 0.5f * body.height, 0.0f}) *
scale({2.0f * body.radius, body.height, 2.0f * body.radius}));
g.renderer.sphere.draw();
軌跡は80個の足元の位置のリングバッファで、3ステップごと(60 Hzで0.05秒)に1つなので、最後の4秒を見せます。
小さな立方体で描き、壁ずりがオンなら水色、オフなら赤です。
Oは視点を、プレイヤーの11 m上、6 m後ろのカメラ(見下ろす)に置き換えます:
if (overhead) {
// O:上から見下ろすデバッグ用のカメラ(遊ぶカメラはそのまま動き続ける) / O: a debug camera looking down from above
// (the gameplay camera keeps working underneath)
Vec3 target = lerp(prevPosition, position, alpha);
view.eye = target + Vec3{0.0f, 11.0f, 6.0f};
view.forward = normalize(target - view.eye);
}
わざと別の視点にしてあります。
遊ぶ為のカメラは裏で動き、ぶつかり続けます。
遊ぶ為のカメラを急に下に向けると、其のスフィアキャストが床に引っ張られてしまいます。
上から見た箱は、レベルのデータの確認にも良いです。
遮蔽は外形全体(2 × 1.1 × 0.5 m)で当たるので、体は斜めの面の少し手前で止まります。
1つの部品に1つの箱は安く、予測し易いので、此れはわざとです。
そして此の章の数字を読むのはF3の行です。
階段でのstepped-upとsnapped-down、台の上の高さ(1.50)、ジャンプ中の縦の速度です。
37.9 動かす
今まで通りビルドし、プロジェクトのルートから./build/games/tps/tpsを動かします(Visual Studioではtpsのプロジェクトを開始します。作業ディレクトリは既にルートです)。
試してみる事:
- BとOをオンにして斜めに壁に向かって歩き、Lを押してもう一度やって下さい。軌跡が違いを見せます。
- F3をオンにして階段を上り、
stepped-upと高さを見て下さい。下りではsnapped-downを見て下さい。体は下までgroundedの儘です。 - 木箱と遮蔽に跳び乗り(どちらも走りながらのジャンプで乗れます)、台にも試して下さい(乗れません)。
- 台の縁から歩き出て、直後にスペースを押して下さい。コヨーテタイムがまだジャンプさせてくれます。ジャンプからの着地の直前にスペースを押すと、先行入力で着地と同時にまた跳びます。
F3の帯の数は、何もおかしくなっていない事の簡単な確認です。
平らな地面ではcontactsは1(床)、壁に向かうと2、角では3です。
37.10 プラットフォームごとの注意
- 全て:物理は
floatと固定ステップを使うので、同じビルドなら同じ入力の実行は毎回同じです。スクリプトで撮った動画は其れに頼っています。其れでもコンパイラやCPUが違うと最後の数ビットが変わる事があります。例えば、コンパイラが掛け算と足し算を1つのFMA命令にまとめる時です(FMAが必ずあるARM64では、GCCとClangは其うする事があります)。其の為、軌跡が機械によって1ミリ未満ずれる事があります。 - Windows(Visual Studio):
<windows.h>はnearとfarをマクロとして定義するので、deepestContactのブロードフェーズの箱はnearではなくreachという名前です。ゲーム自体は<windows.h>を読み込みませんが、GLADや他のヘッダーが読み込む事があります。 - Linux、FreeBSD:特に無し。コードは
<algorithm>と<cmath>しか使いません。
37.11 本物のエンジンではどうしているか
- キャラクターコントローラー:PhysXのキャラクターコントローラー(Unityの
CharacterControllerが使う物)、JoltのCharacterVirtual、UnrealのCharacterMovementComponent、GodotのCharacterBody3Dとmove_and_slideは、どれも物理シミュレーションではなくコードで動かすカプセルです。殆どはカプセルをスイープし(シェイプキャスト)、最初の接触まで動き、残りをあたし達と同じ射影で面に沿って滑らせ、其れを何回か繰り返します。数センチの隙間であるスキン幅(又はコンタクトオフセット)を保ち、次のスイープが面の中から始まらない様にします。Joltのバーチャルキャラクターは接触を集めてまとめて解く事もしていて、あたし達の押し出しに近いです。 - 段差と坂:どのコントローラーにも、名前は違っても同じ2つの設定があります。Unityの
CharacterControllerにはstepOffset(あたし達のstepHeight。マニュアルは身長2 mの人なら0.1〜0.4 mを勧めています)と度で表すslopeLimitがあり、UnrealのCharacterMovementComponentにはMaxStepHeightと、既定で約45°のWalkableFloorAngleがあり、GodotのCharacterBody3Dにはfloor_max_angle(既定45°)と、あたし達の吸い付きに当たるfloor_snap_length(既定0.1 m)があります。Quakeのゲームは段差を逆の順で扱いました。QuakeWorldの地上の移動は、普通の動きと18ユニット高い所からの動きの両方を試し、最後に下ろして、遠くまで行けた方を残します。Quake IIIのPM_StepSlideMoveは、普通の動きが塞がれた時だけ高い所からの動きを試します。Quake IIIは法線の上向きの成分が0.7以上の面を歩ける面とし、此れはあたし達のgroundNormalYと同じ数です。 - 床を探す:押し出しのおまけではなく、エンジンは普通、毎回の移動の後でカプセルを数センチ下へスイープします(又はレイを飛ばします)。其れで床の法線と距離が直接分かり、綺麗に吸い付き、坂と縁を区別出来ます。
- ブロードフェーズ:何千もの当たり判定があると、「全部の箱を調べる」ループは近くの物を探す構造に置き換えます。一様な格子、バウンディングボリューム階層(PhysX、Jolt、BulletはBVHの様な木を使います)、又はスイープ・アンド・プルーンです。
- 本物の坂とメッシュ:レベルは普通三角形のメッシュで、コントローラーは三角形に対して判定する(同じ一番近い点の考えを、箱ではなく三角形で)か、アーティストが見える物と一緒に作る簡単な当たり判定用のメッシュに対して判定します。
- ゲームの手触り:現実より重い重力、空中制御、コヨーテタイム、ジャンプの先行入力は定番です。多くのゲームは更に、上る時より落ちる時の重力を強くし、ボタンを早く離すとジャンプを短く切ります(可変のジャンプの高さ)。
37.12 まとめ
- 体:縦のカプセル、半径0.35 m、高さ1.8 m、baseは足元。引っかかる角が無く、底は丸く、どの方向からも同じ。
- カプセルと箱:芯の線分が縦なので、線分の一番近い点は箱の真ん中の高さを線分にクランプした物。後は球と箱:箱の一番近い点(軸ごとのクランプ)、距離、深さ、法線。箱の中の中心は一番近い面から出る。
deepestContactは先にカプセルのboundsで調べる(ブロードフェーズ)。 - 動いてから押し出す:「一番深い接触、深さ + 0.1 mmだけ外へ」を最大4回。簡単で、どんな重なりも直し、角も扱える。代わりにトンネリングが起こり得る。
- サブステップ:最大 mの部分に分けて、球の中心を全ての箱の外に保つ。分かれるのは10.5 m/sより速い動きだけ。サブステップ無しでは、0.05 mの箱は30 m/sの落下の4回に1回すり抜けられる。
- 壁ずり:の時。45°で6 m/sで壁に当たると壁に沿って4.24 m/s、滑らないと0.77 m/sでじりじり進む。着地と天井にぶつかる事も同じ射影。
- 地面:の接触、傾きが45.57°より小さい面。箱の縁は、球の中心が縁から0.25 m以内の間は地面。
- ジャンプ:重力20 m/s²、ジャンプ7 m/s、理論上 m、固定ステップでは1.167 m。空中制御は毎秒12の代わりに2.5。コヨーテタイムと先行入力は其々0.1秒。終端速度30 m/s。空中の脚の姿勢を毎秒12で混ぜる。
- 階段:下の球を低い縁(最大0.3 m、地面にいる時だけ、縁に向かう時だけ)の上にだけ持ち上げる、小さな曲がった坂。下りでは最大0.3 mまで5 cmずつ下ろして次の段に吸い付け、地面から離れない。
- デバッグ表示:B(箱、カプセル、軌跡)、O(上から)、L(壁ずりオフ)、F3(体の状態)。
37.13 課題
- ★
kGravityを9.81にし、同じ理論上の高さ1.225 mになるジャンプの速さを計算して下さい。 m/sで、滞空時間は0.7秒ではなく1.0秒になるはずです。ゲームで試すと、ジャンプは大体同じ高さ(固定ステップで1.18 m)に届きますが、ふわふわして感じるはずです。 - ★ 下の球の中心が箱の縁からどれだけ外に出ると、接触が地面でなくなるでしょう?
groundNormalYが0.7なら0.25 mになるはずです。0.95の場合と、其の時許される角度を計算して下さい。0.109 mと18.2°になるはずです。 - ★★ トンネリングを起こして下さい。
advanceでint pieces = 1;にし、レベルの地面のsolidを厚さ0.05 mにし(solid -16 -0.05 -16 16 0 16)、出発点を25 mの高さにします(spawn 0 25 11.5 0)。出発点の高さを25.00から25.99 mまで数センチずつ変えて試すと、約4回に1回は床をすり抜けて出現し直し続け、他は着地するはずです。サブステップを戻せば、どの高さでも着地するはずです。 - ★ 吸い付きを分ける理由を見て下さい。
moveのpiecesを1にして0.3 mを一度に落とす様にし、F3とBをオンにして階段を下ります。6段のうち2段でairborneが約0.12秒出て、残りの4段では体が前へ跳ねる所で軌跡に約0.2 mの隙間が出来るはずです。6回に戻すと、下りでairborneは一度も出ず、軌跡の点は等間隔に並ぶはずです。 - ★★ 動く床:x方向に3 mの幅で周期4秒の正弦で往復する2 × 0.5 × 2 mの箱を足し(
g.level.solidsの写しに1つ足して、毎ステップ更新します)、デバッグの立方体で描き、resolveでどの箱が地面の接触だったかを覚えて下さい。体が動く箱の上に立っている時は、移動の前に、此のステップの箱の動きを体の位置に足します。其の上に跳び乗って(0.5 mは段差として上るには高過ぎます)じっとしていると、兵士は一緒に運ばれるはずです。運ぶ処理が無いと、箱は兵士の下から滑って行き、兵士は其の縁から落ちるはずです。 - ★★★ 押し出しをスイープするカプセルに置き換えて下さい。各箱をxとzには半径だけ、yにはカプセルの両端の分だけ大きくし(
sphereCastと同じく角は尖った儘で)、足元の道筋をレイとして飛ばし、衝突の時刻の1 mm手前まで動き、残りの動きを当たった法線に沿って滑らせ、此れを最大3回繰り返します。サブステップ無しでも、課題3の0.05 mの床は一度もすり抜けないはずです。其れから柱の角に触れながら回って下さい。押し出しの時より大回りするはずです。角の尖った大きくした箱の代償です。 - ★★★ しゃがむ:左Ctrlで高さを1.8 mから1.1 mにし(足元は其の儘)、カメラのピボットも一緒に下げ、足元に全高のカプセルを置くと何かと重なる間(
deepestContact({position, radius, 1.8f}, solids))は立ち上がるのを拒んで下さい。出発点の前にsolid -1 1.2 8 1 1.5 9で梁を足します。立っていると兵士は其処で止まり、しゃがむと其の下を歩けて、下でCtrlを離しても出るまでしゃがんだ儘のはずです。
ファイル: a/games/tps/CMakeLists.txt | b/games/tps/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,6 +2,7 @@ | |||
| 2 | add_executable(tps | 2 | add_executable(tps |
| 3 | src/main.cc | 3 | src/main.cc |
| 4 | src/collision3d.cc | 4 | src/collision3d.cc |
| 5 | src/character_body.cc | ||
| 5 | src/frustum.cc | 6 | src/frustum.cc |
| 6 | src/level.cc | 7 | src/level.cc |
| 7 | src/renderer.cc | 8 | src/renderer.cc |
ファイル: a/games/tps/README.md | b/games/tps/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -7,15 +7,18 @@ | |||
| 7 | ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row | 7 | ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row |
| 8 | ``` | 8 | ``` |
| 9 | 9 | ||
| 10 | ## 操作 / Controls(第36章 / chapter 36) | 10 | ## 操作 / Controls(第36・37章 / chapters 36-37) |
| 11 | 11 | ||
| 12 | | キー / key | | | 12 | | キー / key | | |
| 13 | |---|---| | 13 | |---|---| |
| 14 | | WASD / ↑↓←→ | カメラの向きに対して移動 / move relative to the camera | | 14 | | WASD / ↑↓←→ | カメラの向きに対して移動 / move relative to the camera | |
| 15 | | マウス / mouse | 見回す / look around | | 15 | | マウス / mouse | 見回す / look around | |
| 16 | | Shift | 走る(前へ) / run (forwards) | | 16 | | Shift | 走る(前へ) / run (forwards) | |
| 17 | | Space | ジャンプ / jump | | ||
| 17 | | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder | | 18 | | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder | |
| 18 | | B | 当たり判定の箱とソケット / collision boxes and sockets | | 19 | | B | 当たり判定の箱・カプセル・軌跡・ソケット / collision boxes, capsule, trail, sockets | |
| 20 | | O | 上から見下ろす(デバッグ) / view from above (debugging) | | ||
| 21 | | L | 壁ずり ⇔ 壁で止まる / wall sliding ⇔ stopping at walls | | ||
| 19 | | C | カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | | 22 | | C | カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | |
| 20 | | K | カメラの当たり判定のオン・オフ / camera collision on / off | | 23 | | K | カメラの当たり判定のオン・オフ / camera collision on / off | |
| 21 | | P | 手続き的な姿勢のオン・オフ / procedural pose on / off | | 24 | | P | 手続き的な姿勢のオン・オフ / procedural pose on / off | |
| @@ -31,7 +34,8 @@ src/main.cc ウィンドウ、読み込み、ゲームループ | |||
| 31 | src/game.hh シーンが共有するデータ / data the scenes share | 34 | src/game.hh シーンが共有するデータ / data the scenes share |
| 32 | src/play_scene.* 遊ぶシーン / the play scene | 35 | src/play_scene.* 遊ぶシーン / the play scene |
| 33 | src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling | 36 | src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling |
| 34 | src/collision3d.* AABB、レイ、スフィアキャスト / AABBs, rays, sphere casts | 37 | src/collision3d.* AABB、レイ、スフィアキャスト、カプセルと箱 / AABBs, rays, sphere casts, capsule vs box |
| 38 | src/character_body.* 当たり判定・重力・壁ずり・段差 / collision, gravity, wall sliding, steps | ||
| 35 | src/frustum.* 視錐台の平面 / frustum planes | 39 | src/frustum.* 視錐台の平面 / frustum planes |
| 36 | src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post | 40 | src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post |
| 37 | src/character.* 関節の姿勢と腕のIK / joint poses and arm IK | 41 | src/character.* 関節の姿勢と腕のIK / joint poses and arm IK |
ファイル: a/games/tps/src/character.cc | b/games/tps/src/character.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -117,11 +117,16 @@ void applyPose(Model &model, const Model &weapon, const CharacterRig &rig, const | |||
| 117 | // 脚:太ももを前後に振り、前へ出ていく脚の膝を曲げる(足を持ち上げる) / legs: swing the thighs back and forth and | 117 | // 脚:太ももを前後に振り、前へ出ていく脚の膝を曲げる(足を持ち上げる) / legs: swing the thighs back and forth and |
| 118 | // bend the knee of the leg that swings forward (lifting the foot) | 118 | // bend the knee of the leg that swings forward (lifting the foot) |
| 119 | float swing = 0.5f * pose.stride * w * std::sin(phase); | 119 | float swing = 0.5f * pose.stride * w * std::sin(phase); |
| 120 | // 空中(第37章):左の太ももを前へ、右を後ろへ、両膝を曲げる。地面の姿勢とairで混ぜる | ||
| 121 | // Airborne (chapter 37): left thigh forward, right thigh back, both knees bent; mixed with the ground pose by `air` | ||
| 122 | const float airThigh[2] = {-0.55f, 0.25f}, airKnee[2] = {0.9f, 0.6f}; | ||
| 120 | for (int s = 0; s < 2; ++s) { | 123 | for (int s = 0; s < 2; ++s) { |
| 121 | float sign = s == 0 ? 1.0f : -1.0f; // 左右は逆位相 / left and right are in opposite phase | 124 | float sign = s == 0 ? 1.0f : -1.0f; // 左右は逆位相 / left and right are in opposite phase |
| 122 | node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(-sign * swing); | 125 | float thigh = -sign * swing * (1.0f - pose.air) + airThigh[s] * pose.air; |
| 126 | node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(thigh); | ||
| 123 | float forwardSwing = std::fmax(0.0f, sign * std::cos(phase)); // この脚が前へ動いている / this leg moves forward | 127 | float forwardSwing = std::fmax(0.0f, sign * std::cos(phase)); // この脚が前へ動いている / this leg moves forward |
| 124 | node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(w * pose.stride * (0.12f + 1.0f * forwardSwing)); | 128 | float knee = w * pose.stride * (0.12f + 1.0f * forwardSwing) * (1.0f - pose.air) + airKnee[s] * pose.air; |
| 129 | node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(knee); | ||
| 125 | } | 130 | } |
| 126 | 131 | ||
| 127 | // 上半身:腰の回転を打ち消して狙う向きを保つ。狙いの上下は背骨・頭・銃で分ける。走ると少し前かがみ | 132 | // 上半身:腰の回転を打ち消して狙う向きを保つ。狙いの上下は背骨・頭・銃で分ける。走ると少し前かがみ |
ファイル: a/games/tps/src/character.hh | b/games/tps/src/character.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -30,6 +30,8 @@ struct CharacterPose { | |||
| 30 | float stride = 1.0f; // 足の振りの大きさ(走ると大きい) / leg swing size (bigger when running) | 30 | float stride = 1.0f; // 足の振りの大きさ(走ると大きい) / leg swing size (bigger when running) |
| 31 | float legYaw = 0.0f; // 腰から下を移動の向きへ回す(ラジアン) / turns the legs towards the movement (radians) | 31 | float legYaw = 0.0f; // 腰から下を移動の向きへ回す(ラジアン) / turns the legs towards the movement (radians) |
| 32 | float aimPitch = 0.0f; // 銃の上下(ラジアン、正 = 上) / the gun's pitch (radians, positive = up) | 32 | float aimPitch = 0.0f; // 銃の上下(ラジアン、正 = 上) / the gun's pitch (radians, positive = up) |
| 33 | float air = 0.0f; // 0 = 地面、1 = 空中(脚を縮める、第37章) / 0 = on the ground, 1 = airborne (legs tucked, | ||
| 34 | // chapter 37) | ||
| 33 | }; | 35 | }; |
| 34 | 36 | ||
| 35 | // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、 | 37 | // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、 |
ファイル: /dev/null | b/games/tps/src/character_body.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,108 @@ | |||
| 1 | #include "character_body.hh" | ||
| 2 | |||
| 3 | #include <algorithm> | ||
| 4 | #include <cmath> | ||
| 5 | |||
| 6 | void CharacterBody::restore(const State &s) { | ||
| 7 | position = s.position; | ||
| 8 | velocity = s.velocity; | ||
| 9 | grounded = s.grounded; | ||
| 10 | hitWall = s.hitWall; | ||
| 11 | steppedUp = s.steppedUp; | ||
| 12 | contacts = s.contacts; | ||
| 13 | } | ||
| 14 | |||
| 15 | bool CharacterBody::blockedAt(Vec3 feet, std::span<const Aabb> solids) const { | ||
| 16 | return deepestContact({feet, radius, height}, solids).has_value(); | ||
| 17 | } | ||
| 18 | |||
| 19 | void CharacterBody::resolve(std::span<const Aabb> solids) { | ||
| 20 | // 一番深い接触から順に押し出す(角では2〜3枚に同時に当たる) / push out of the deepest contact first (in a corner | ||
| 21 | // it touches two or three boxes at once) | ||
| 22 | for (int iteration = 0; iteration < 4; ++iteration) { | ||
| 23 | std::optional<Contact> c = deepestContact(capsule(), solids); | ||
| 24 | if (!c) break; | ||
| 25 | ++contacts; | ||
| 26 | if (stepping && c->normal.y <= groundNormalY && climb(solids[static_cast<size_t>(c->index)])) continue; | ||
| 27 | position = position + (c->depth + 1e-4f) * c->normal; | ||
| 28 | bool ground = c->normal.y > groundNormalY; | ||
| 29 | if (ground) grounded = true; | ||
| 30 | else if (c->normal.y > -groundNormalY) hitWall = true; // 天井はどちらでもない / a ceiling is neither | ||
| 31 | float into = dot(velocity, c->normal); | ||
| 32 | if (into >= 0.0f) continue; // もう離れていく / already moving away | ||
| 33 | if (slide || ground) { | ||
| 34 | // 壁ずり:面に向かう成分だけを消す。残りは面に沿う速度 / wall slide: remove only the part towards the | ||
| 35 | // surface; what remains runs along it | ||
| 36 | velocity = velocity - into * c->normal; | ||
| 37 | } else { | ||
| 38 | // 比べる用:壁に当たったら水平に止まる(ゲームでは引っかかって動けなくなる) / for comparison: stop horizontally | ||
| 39 | // at a wall (in a game you get stuck on every corner) | ||
| 40 | velocity = {0.0f, std::fmin(velocity.y, 0.0f), 0.0f}; | ||
| 41 | } | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | bool CharacterBody::climb(const Aabb &box) { | ||
| 46 | // 下の球が低い箱の角に当たった(箱の上面が足元からstepHeight以内で、下の球の中心より下):横に押し返す代わりに、 | ||
| 47 | // 球がその角に乗る高さまで真上に持ち上げる。近づくほど持ち上がるので、段差は小さな坂のように上れる | ||
| 48 | // The lower sphere touches the edge of a low box (its top within stepHeight of the feet and below the lower | ||
| 49 | // sphere's center): instead of pushing back sideways, lift straight up until the sphere rests on that edge. The | ||
| 50 | // closer it gets, the higher it is lifted, so a step is climbed like a small ramp | ||
| 51 | float rise = box.hi.y - position.y; | ||
| 52 | if (rise <= 0.0f || rise > stepHeight || box.hi.y > position.y + radius) return false; | ||
| 53 | Vec3 centre = position + Vec3{0.0f, radius, 0.0f}; | ||
| 54 | Vec3 q = closestPoint(box, centre); | ||
| 55 | Vec3 toEdge = {q.x - centre.x, 0.0f, q.z - centre.z}; | ||
| 56 | float flat = length(toEdge); | ||
| 57 | // 向かっている段だけ:離れていく段(下りるときの今の段)の角に乗せ直すと、体が角に引っかかって浮く | ||
| 58 | // Only a step we are moving towards: lifting the body back onto the edge of a step it is leaving (going down) | ||
| 59 | // would leave it hanging on that edge | ||
| 60 | if (flat >= radius || dot(toEdge, velocity) <= 0.0f) return false; | ||
| 61 | float lift = box.hi.y + std::sqrt(radius * radius - flat * flat) - centre.y + 1e-4f; | ||
| 62 | if (lift <= 0.0f || blockedAt(position + Vec3{0.0f, lift, 0.0f}, {&box, 1})) return false; | ||
| 63 | position.y += lift; | ||
| 64 | velocity.y = std::fmax(velocity.y, 0.0f); | ||
| 65 | grounded = steppedUp = true; | ||
| 66 | return true; | ||
| 67 | } | ||
| 68 | |||
| 69 | void CharacterBody::advance(float dt, std::span<const Aabb> solids) { | ||
| 70 | // 一度に半径の半分より進まない:速くても薄い箱をすり抜けない(トンネリング) / never move more than half the | ||
| 71 | // radius at once, so fast motion does not tunnel through thin boxes | ||
| 72 | float distance = length(velocity) * dt; | ||
| 73 | int pieces = std::max(1, static_cast<int>(std::ceil(distance / (0.5f * radius)))); | ||
| 74 | float h = dt / static_cast<float>(pieces); | ||
| 75 | for (int i = 0; i < pieces; ++i) { | ||
| 76 | position = position + h * velocity; | ||
| 77 | resolve(solids); | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | void CharacterBody::move(float dt, std::span<const Aabb> solids, bool canStep) { | ||
| 82 | bool wasGrounded = grounded; | ||
| 83 | grounded = hitWall = steppedUp = snappedDown = false; | ||
| 84 | contacts = 0; | ||
| 85 | stepping = canStep && wasGrounded; // 段差を上ってよいのは地面にいたときだけ / climb ledges only from the ground | ||
| 86 | advance(dt, solids); | ||
| 87 | |||
| 88 | // 下りの段差に吸い付く:さっきまで地面にいて、跳んでいないなら、stepHeightまで下に地面を探す。一度に下ろすと | ||
| 89 | // 今の段の角に深くめり込み、角の斜めの法線で前へ押し出される(跳ねる、届かない)ので、5 cmずつ下ろして | ||
| 90 | // 地面に着いた所で止める | ||
| 91 | // Stick to the ground going down a step: if it was grounded a moment ago and did not jump, look for ground up to | ||
| 92 | // stepHeight below. Dropping it all at once would sink deep into the edge of the step it is leaving, and the edge's | ||
| 93 | // tilted normal would push it forward (a hop, or a miss), so lower it 5 cm at a time and stop on the first ground | ||
| 94 | if (canStep && wasGrounded && !grounded && velocity.y <= 0.0f) { | ||
| 95 | State before = save(); | ||
| 96 | const int pieces = 6; // 0.3 m / 6 = 5 cm | ||
| 97 | for (int i = 0; i < pieces && !grounded; ++i) { | ||
| 98 | position.y -= stepHeight / static_cast<float>(pieces); | ||
| 99 | resolve(solids); | ||
| 100 | } | ||
| 101 | if (grounded) { | ||
| 102 | snappedDown = true; | ||
| 103 | velocity.y = 0.0f; | ||
| 104 | } else { | ||
| 105 | restore(before); | ||
| 106 | } | ||
| 107 | } | ||
| 108 | } | ||
ファイル: /dev/null | b/games/tps/src/character_body.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,59 @@ | |||
| 1 | // キャラクターの体(第37章):縦のカプセルを、レベルの箱にめり込まないように動かす。 | ||
| 2 | // ・速度で少しずつ進み(サブステップ)、めり込んだら一番深い接触の法線の向きに押し出す | ||
| 3 | // ・壁ずり:速度から壁に向かう成分を引く v' = v − (v·n) n (線型代数の第4章、射影) | ||
| 4 | // ・法線が上を向いた接触(n.y > 0.7)は地面:着地 | ||
| 5 | // ・段差(stepHeight以下)は上る:下の球が低い箱の角に当たったら、横ではなく真上に押し上げる | ||
| 6 | // ・地面にいたのに足元が消えたら(階段を下りる)stepHeightまで少しずつ下に吸い付ける | ||
| 7 | // A character's body (chapter 37): moves an upright capsule without letting it sink into the level's boxes. | ||
| 8 | // - advance by the velocity in small pieces (sub-steps); when it penetrates, push out along the deepest contact's | ||
| 9 | // normal | ||
| 10 | // - wall sliding: remove the part of the velocity that goes into the wall v' = v − (v·n) n (Linear Algebra | ||
| 11 | // chapter 4, projection) | ||
| 12 | // - a contact whose normal points up (n.y > 0.7) is ground: landed | ||
| 13 | // - small ledges (up to stepHeight) are climbed: when the lower sphere hits the edge of a low box, it is pushed up | ||
| 14 | // instead of sideways | ||
| 15 | // - if the ground vanishes under a grounded body (walking down stairs), it is snapped down, in small pieces, by up | ||
| 16 | // to stepHeight | ||
| 17 | #pragma once | ||
| 18 | |||
| 19 | #include "collision3d.hh" | ||
| 20 | |||
| 21 | #include <span> | ||
| 22 | |||
| 23 | class CharacterBody { | ||
| 24 | public: | ||
| 25 | Vec3 position; // 足元(カプセルの底) / the feet (the bottom of the capsule) | ||
| 26 | Vec3 velocity; // m/s。重力は呼ぶ側が足す / m/s. The caller adds gravity | ||
| 27 | float radius = 0.35f; | ||
| 28 | float height = 1.8f; | ||
| 29 | float stepHeight = 0.3f; // これ以下の段差は自動で上る / ledges up to this height are climbed automatically | ||
| 30 | float groundNormalY = 0.7f; // n.yがこれより大きい面は地面(約45°まで) / n.y above this = ground (up to ~45°) | ||
| 31 | bool slide = true; // false:壁に当たると止まる(比べるため、L) / false: stop at walls (to compare, L) | ||
| 32 | |||
| 33 | // 最後のmoveの結果 / results of the last move | ||
| 34 | bool grounded = false; | ||
| 35 | bool hitWall = false; | ||
| 36 | bool steppedUp = false; | ||
| 37 | bool snappedDown = false; | ||
| 38 | int contacts = 0; // 押し出した回数 / how many times it was pushed out | ||
| 39 | |||
| 40 | Capsule capsule() const { return {position, radius, height}; } | ||
| 41 | // 1ステップ動かす。canStep = 段差を上る・下りるか(空中ではfalseで良い) / one step. canStep = climb / snap | ||
| 42 | // ledges (may be false in the air) | ||
| 43 | void move(float dt, std::span<const Aabb> solids, bool canStep = true); | ||
| 44 | // その位置に置いたらめり込むか / would the body penetrate something at this position? | ||
| 45 | bool blockedAt(Vec3 feet, std::span<const Aabb> solids) const; | ||
| 46 | |||
| 47 | private: | ||
| 48 | struct State { | ||
| 49 | Vec3 position, velocity; | ||
| 50 | bool grounded, hitWall, steppedUp; | ||
| 51 | int contacts; | ||
| 52 | }; | ||
| 53 | State save() const { return {position, velocity, grounded, hitWall, steppedUp, contacts}; } | ||
| 54 | void restore(const State &s); | ||
| 55 | void advance(float dt, std::span<const Aabb> solids); // サブステップで進む / advance in sub-steps | ||
| 56 | void resolve(std::span<const Aabb> solids); // めり込みを直す / fix penetrations | ||
| 57 | bool climb(const Aabb &box); // 段差に乗る / step onto a ledge | ||
| 58 | bool stepping = false; // このmoveで段差を上ってよいか / may climb in this move | ||
| 59 | }; | ||
ファイル: a/games/tps/src/collision3d.cc | b/games/tps/src/collision3d.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -89,3 +89,45 @@ std::optional<RayHit> sphereCast(const Ray &ray, float radius, std::span<const A | |||
| 89 | } | 89 | } |
| 90 | return best; | 90 | return best; |
| 91 | } | 91 | } |
| 92 | |||
| 93 | Vec3 closestPoint(const Aabb &box, Vec3 p) { | ||
| 94 | return {std::clamp(p.x, box.lo.x, box.hi.x), std::clamp(p.y, box.lo.y, box.hi.y), std::clamp(p.z, box.lo.z, box.hi.z)}; | ||
| 95 | } | ||
| 96 | |||
| 97 | std::optional<Contact> sphereAabb(Vec3 centre, float radius, const Aabb &box) { | ||
| 98 | Vec3 q = closestPoint(box, centre); | ||
| 99 | Vec3 d = centre - q; | ||
| 100 | float dist2 = dot(d, d); | ||
| 101 | if (dist2 >= radius * radius) return std::nullopt; | ||
| 102 | if (dist2 > 1e-12f) { | ||
| 103 | float dist = std::sqrt(dist2); | ||
| 104 | return Contact{d / dist, radius - dist, -1}; | ||
| 105 | } | ||
| 106 | // 中心が箱の中:一番近い面から外へ / the center is inside the box: out through the nearest face | ||
| 107 | const float gaps[6] = {centre.x - box.lo.x, box.hi.x - centre.x, centre.y - box.lo.y, | ||
| 108 | box.hi.y - centre.y, centre.z - box.lo.z, box.hi.z - centre.z}; | ||
| 109 | const Vec3 normals[6] = {{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}}; | ||
| 110 | int best = 0; | ||
| 111 | for (int i = 1; i < 6; ++i) | ||
| 112 | if (gaps[i] < gaps[best]) best = i; | ||
| 113 | return Contact{normals[best], gaps[best] + radius, -1}; | ||
| 114 | } | ||
| 115 | |||
| 116 | std::optional<Contact> capsuleAabb(const Capsule &capsule, const Aabb &box) { | ||
| 117 | float y = std::clamp(0.5f * (box.lo.y + box.hi.y), capsule.bottomY(), capsule.topY()); | ||
| 118 | return sphereAabb({capsule.base.x, y, capsule.base.z}, capsule.radius, box); | ||
| 119 | } | ||
| 120 | |||
| 121 | std::optional<Contact> deepestContact(const Capsule &capsule, std::span<const Aabb> boxes) { | ||
| 122 | std::optional<Contact> best; | ||
| 123 | Aabb reach = capsule.bounds(); | ||
| 124 | for (size_t i = 0; i < boxes.size(); ++i) { | ||
| 125 | if (!overlaps(reach, boxes[i])) continue; // 大まかな判定(ブロードフェーズ) / the coarse test (broad phase) | ||
| 126 | std::optional<Contact> c = capsuleAabb(capsule, boxes[i]); | ||
| 127 | if (c && (!best || c->depth > best->depth)) { | ||
| 128 | best = c; | ||
| 129 | best->index = static_cast<int>(i); | ||
| 130 | } | ||
| 131 | } | ||
| 132 | return best; | ||
| 133 | } | ||
ファイル: a/games/tps/src/collision3d.hh | b/games/tps/src/collision3d.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,6 +1,7 @@ | |||
| 1 | // 3Dの当たり判定(第36章):軸に平行な箱(AABB)と、レイ・球を飛ばすテスト。カメラが壁にめり込まないために使う | 1 | // 3Dの当たり判定(第36・37章):軸に平行な箱(AABB)、レイ・球を飛ばすテスト(カメラ、第36章)、 |
| 2 | // 3D collision (chapter 36): axis-aligned boxes (AABBs) and ray / sphere casts. The camera uses them to stay out of | 2 | // 縦のカプセル・球と箱のめり込み(キャラクター、第37章) |
| 3 | // the walls | 3 | // 3D collision (chapters 36-37): axis-aligned boxes (AABBs), ray / sphere casts (the camera, chapter 36) and the |
| 4 | // penetration of upright capsules / spheres into boxes (the characters, chapter 37) | ||
| 4 | #pragma once | 5 | #pragma once |
| 5 | 6 | ||
| 6 | #include "engine/mathx.hh" | 7 | #include "engine/mathx.hh" |
| @@ -49,3 +50,41 @@ std::optional<RayHit> raycast(const Ray &ray, std::span<const Aabb> boxes, float | |||
| 49 | // Casts a sphere of the given radius: a ray against the boxes grown by the radius (the real Minkowski sum has rounded | 50 | // Casts a sphere of the given radius: a ray against the boxes grown by the radius (the real Minkowski sum has rounded |
| 50 | // corners, so near corners this stops a little early, which is the safe side for a camera) | 51 | // corners, so near corners this stops a little early, which is the safe side for a camera) |
| 51 | std::optional<RayHit> sphereCast(const Ray &ray, float radius, std::span<const Aabb> boxes, float maxT); | 52 | std::optional<RayHit> sphereCast(const Ray &ray, float radius, std::span<const Aabb> boxes, float maxT); |
| 53 | |||
| 54 | // 箱の中で点pに一番近い点(各軸でクランプ) / the point of the box nearest to p (clamp per axis) | ||
| 55 | Vec3 closestPoint(const Aabb &box, Vec3 p); | ||
| 56 | |||
| 57 | // めり込み:normalの向きにdepthだけ動かすと離れる(normalは箱から外向きの単位ベクトル) / a penetration: moving by depth | ||
| 58 | // along normal separates them (normal = unit vector pointing out of the box) | ||
| 59 | struct Contact { | ||
| 60 | Vec3 normal; | ||
| 61 | float depth = 0.0f; | ||
| 62 | int index = -1; | ||
| 63 | }; | ||
| 64 | |||
| 65 | // 球と箱 / sphere against box | ||
| 66 | std::optional<Contact> sphereAabb(Vec3 centre, float radius, const Aabb &box); | ||
| 67 | |||
| 68 | // 縦に立ったカプセル(第37章のキャラクターの体):底の点base、半径radius、全体の高さheight(≥ 2·radius)。 | ||
| 69 | // 中心の線分は base + (0, radius, 0) から base + (0, height − radius, 0) まで | ||
| 70 | // An upright capsule (the characters' body, chapter 37): bottom point base, radius, total height (≥ 2·radius). Its | ||
| 71 | // core segment runs from base + (0, radius, 0) to base + (0, height − radius, 0) | ||
| 72 | struct Capsule { | ||
| 73 | Vec3 base; | ||
| 74 | float radius = 0.35f; | ||
| 75 | float height = 1.8f; | ||
| 76 | |||
| 77 | float bottomY() const { return base.y + radius; } // 下の球の中心の高さ / height of the lower sphere's center | ||
| 78 | float topY() const { return base.y + height - radius; } // 上の球の中心の高さ / height of the upper sphere's center | ||
| 79 | Aabb bounds() const { | ||
| 80 | return {{base.x - radius, base.y, base.z - radius}, {base.x + radius, base.y + height, base.z + radius}}; | ||
| 81 | } | ||
| 82 | }; | ||
| 83 | |||
| 84 | // カプセルと箱。線分が縦なので簡単:線分の中で箱に一番近い高さyを選べば(箱の高さの真ん中を線分の範囲に | ||
| 85 | // クランプ)、あとはその高さの球と箱の問題になる | ||
| 86 | // Capsule against box. The segment is vertical, which makes it easy: pick the height y on the segment nearest to the | ||
| 87 | // box (the box's middle height clamped to the segment), then it is a sphere at that height against the box | ||
| 88 | std::optional<Contact> capsuleAabb(const Capsule &capsule, const Aabb &box); | ||
| 89 | // 一番深いめり込み(なければnullopt) / the deepest penetration among the boxes (nullopt if none) | ||
| 90 | std::optional<Contact> deepestContact(const Capsule &capsule, std::span<const Aabb> boxes); | ||
ファイル: a/games/tps/src/main.cc | b/games/tps/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,16 +1,21 @@ | |||
| 1 | // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ | 1 | // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 |
| 2 | // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera | 2 | // ジャンプ、壁ずり |
| 3 | // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera. | ||
| 4 | // Chapter 37: collision, gravity, jumping, wall sliding | ||
| 3 | // | 5 | // |
| 4 | // 操作 / Controls: | 6 | // 操作 / Controls: |
| 5 | // WASD カメラの向きに対して移動 / move relative to the camera | 7 | // WASD カメラの向きに対して移動 / move relative to the camera |
| 6 | // マウス / mouse 見回す / look around | 8 | // マウス / mouse 見回す / look around |
| 7 | // Shift 走る(前へ) / run (forwards) | 9 | // Shift 走る(前へ) / run (forwards) |
| 10 | // Space ジャンプ / jump | ||
| 8 | // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder | 11 | // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder |
| 9 | // B 当たり判定の箱 / collision boxes | 12 | // B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail |
| 10 | // F3 時間と描いた数 / timings and draw counts | 13 | // F3 時間と描いた数 / timings and draw counts |
| 11 | // F4 視錐台カリングのオン・オフ / frustum culling on / off | 14 | // F4 視錐台カリングのオン・オフ / frustum culling on / off |
| 12 | // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | 15 | // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) |
| 13 | // K カメラの当たり判定のオン・オフ / camera collision on / off | 16 | // K カメラの当たり判定のオン・オフ / camera collision on / off |
| 17 | // O 上から見下ろす(デバッグ) / view from above (debugging) | ||
| 18 | // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) | ||
| 14 | // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) | 19 | // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) |
| 15 | // Tab カーソルのキャプチャ / cursor capture | 20 | // Tab カーソルのキャプチャ / cursor capture |
| 16 | // Esc 終了 / quit | 21 | // Esc 終了 / quit |
| @@ -56,6 +61,7 @@ int main(int argc, char **argv) { | |||
| 56 | input.bind("left", {InputBinding::key(GLFW_KEY_A), InputBinding::key(GLFW_KEY_LEFT)}); | 61 | input.bind("left", {InputBinding::key(GLFW_KEY_A), InputBinding::key(GLFW_KEY_LEFT)}); |
| 57 | input.bind("right", {InputBinding::key(GLFW_KEY_D), InputBinding::key(GLFW_KEY_RIGHT)}); | 62 | input.bind("right", {InputBinding::key(GLFW_KEY_D), InputBinding::key(GLFW_KEY_RIGHT)}); |
| 58 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT)}); | 63 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT)}); |
| 64 | input.bind("jump", {InputBinding::key(GLFW_KEY_SPACE)}); | ||
| 59 | 65 | ||
| 60 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 66 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 61 | Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, | 67 | Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, |
ファイル: a/games/tps/src/play_scene.cc | b/games/tps/src/play_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -18,6 +18,14 @@ static float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt) | |||
| 18 | constexpr float kWalkSpeed = 3.2f; // m/s | 18 | constexpr float kWalkSpeed = 3.2f; // m/s |
| 19 | constexpr float kRunSpeed = 6.0f; // m/s(Shift) | 19 | constexpr float kRunSpeed = 6.0f; // m/s(Shift) |
| 20 | constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target | 20 | constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target |
| 21 | constexpr float kAirControl = 2.5f; // 空中ではゆっくりしか向きを変えられない / in the air it steers only slowly | ||
| 22 | constexpr float kGravity = 20.0f; // m/s²(現実の約2倍:ゲームでは重めが気持ち良い) / m/s² (about twice the real | ||
| 23 | // value: games feel better heavier) | ||
| 24 | constexpr float kJumpSpeed = 7.0f; // m/s → 高さ1.17 m(60 Hzの固定ステップ。v²/2gなら1.23 m) / m/s → 1.17 m high | ||
| 25 | // with the 60 Hz fixed step (v²/2g would give 1.23 m) | ||
| 26 | constexpr float kCoyoteTime = 0.1f; // 足場を離れてからまだ跳べる時間 / time after leaving a ledge that still allows a jump | ||
| 27 | constexpr float kJumpBuffer = 0.1f; // 着地の少し前に押したジャンプを覚えておく時間 / a jump pressed just before | ||
| 28 | // landing is remembered this long | ||
| 21 | 29 | ||
| 22 | PlayScene::PlayScene(Game &game) : g(game) {} | 30 | PlayScene::PlayScene(Game &game) : g(game) {} |
| 23 | 31 | ||
| @@ -30,7 +38,7 @@ Vec3 PlayScene::cameraPivot() const { | |||
| 30 | } | 38 | } |
| 31 | 39 | ||
| 32 | void PlayScene::enter() { | 40 | void PlayScene::enter() { |
| 33 | position = prevPosition = g.level.spawn; | 41 | body.position = position = prevPosition = g.level.spawn; |
| 34 | heading = prevHeading = g.level.spawnYaw; | 42 | heading = prevHeading = g.level.spawnYaw; |
| 35 | camera.yaw = g.level.spawnYaw; | 43 | camera.yaw = g.level.spawnYaw; |
| 36 | camera.reset(cameraPivot(), g.level.solids); | 44 | camera.reset(cameraPivot(), g.level.solids); |
| @@ -64,6 +72,8 @@ void PlayScene::update(float dt) { | |||
| 64 | if (in.pressed(GLFW_KEY_K)) cameraCollision = !cameraCollision; | 72 | if (in.pressed(GLFW_KEY_K)) cameraCollision = !cameraCollision; |
| 65 | if (in.pressed(GLFW_KEY_P)) posing = !posing; | 73 | if (in.pressed(GLFW_KEY_P)) posing = !posing; |
| 66 | if (in.pressed(GLFW_KEY_F4)) culling = !culling; | 74 | if (in.pressed(GLFW_KEY_F4)) culling = !culling; |
| 75 | if (in.pressed(GLFW_KEY_L)) body.slide = !body.slide; | ||
| 76 | if (in.pressed(GLFW_KEY_O)) overhead = !overhead; | ||
| 67 | 77 | ||
| 68 | // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: | 78 | // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: |
| 69 | // only the first step uses it) | 79 | // only the first step uses it) |
| @@ -80,11 +90,48 @@ void PlayScene::update(float dt) { | |||
| 80 | if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally | 90 | if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally |
| 81 | bool running = in.actionHeld("run") && stick.y > 0.0f; | 91 | bool running = in.actionHeld("run") && stick.y > 0.0f; |
| 82 | Vec3 target = (running ? kRunSpeed : kWalkSpeed) * wish; | 92 | Vec3 target = (running ? kRunSpeed : kWalkSpeed) * wish; |
| 83 | velocity = velocity + approach(kAcceleration, dt) * (target - velocity); | 93 | // 水平の速度だけを目標へ(上下は重力とジャンプ)。空中ではゆっくり / only the horizontal velocity approaches the |
| 84 | position = position + dt * velocity; // 第36章:まだ当たり判定なし / chapter 36: no collision yet | 94 | // target (vertical = gravity and jumps); slowly in the air |
| 95 | Vec3 &v = body.velocity; | ||
| 96 | float k = approach(body.grounded ? kAcceleration : kAirControl, dt); | ||
| 97 | v.x += k * (target.x - v.x); | ||
| 98 | v.z += k * (target.z - v.z); | ||
| 85 | 99 | ||
| 86 | // 3. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ | 100 | // 3. 重力とジャンプ。コヨーテタイム(足場を離れた直後)とジャンプの先行入力(着地の直前)で、押したのに |
| 87 | // 3. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards | 101 | // 跳べないことをなくす |
| 102 | // 3. gravity and jumping. Coyote time (just after leaving a ledge) and a jump buffer (just before landing) make sure | ||
| 103 | // a press is never lost | ||
| 104 | coyote = body.grounded ? kCoyoteTime : coyote - dt; | ||
| 105 | jumpBuffer = in.actionPressed("jump") ? kJumpBuffer : jumpBuffer - dt; | ||
| 106 | bool jumped = false; | ||
| 107 | if (jumpBuffer > 0.0f && coyote > 0.0f) { | ||
| 108 | v.y = kJumpSpeed; | ||
| 109 | jumpBuffer = coyote = 0.0f; | ||
| 110 | jumped = true; | ||
| 111 | ++jumps; | ||
| 112 | } | ||
| 113 | v.y -= kGravity * dt; | ||
| 114 | v.y = std::fmax(v.y, -30.0f); // 終端速度 / terminal velocity | ||
| 115 | body.move(dt, g.level.solids, !jumped); | ||
| 116 | if (body.position.y < -20.0f) { // 落ちたら出発点へ / fell out of the level: back to the start | ||
| 117 | // 補間もカメラも出発点から(下から飛んで来ない) / interpolation and camera restart there too (no swoop from below) | ||
| 118 | body.position = position = prevPosition = g.level.spawn; | ||
| 119 | v = {0.0f, 0.0f, 0.0f}; | ||
| 120 | camera.reset(cameraPivot(), g.level.solids); | ||
| 121 | prevEye = camera.eye(); | ||
| 122 | prevForward = camera.forward(); | ||
| 123 | } | ||
| 124 | position = body.position; | ||
| 125 | Vec3 velocity = body.velocity; // 実際に動いた速度(壁ずりの後) / the velocity after sliding | ||
| 126 | // 軌跡(B):0.05秒ごとに足元を覚える / the trail (B): remember the feet every 0.05 s | ||
| 127 | if (++trailTick % 3 == 0) { | ||
| 128 | trail[trailNext] = position; | ||
| 129 | trailNext = (trailNext + 1) % kTrail; | ||
| 130 | trailCount = std::min(trailCount + 1, kTrail); | ||
| 131 | } | ||
| 132 | |||
| 133 | // 4. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ | ||
| 134 | // 4. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards | ||
| 88 | // the movement | 135 | // the movement |
| 89 | if (!inspect) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt)); | 136 | if (!inspect) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt)); |
| 90 | float speed = length(Vec3{velocity.x, 0.0f, velocity.z}); | 137 | float speed = length(Vec3{velocity.x, 0.0f, velocity.z}); |
| @@ -109,8 +156,11 @@ void PlayScene::update(float dt) { | |||
| 109 | pose.walkAmount = std::clamp(speed / kWalkSpeed, 0.0f, 1.0f); | 156 | pose.walkAmount = std::clamp(speed / kWalkSpeed, 0.0f, 1.0f); |
| 110 | pose.stride = 1.0f + 0.5f * run; | 157 | pose.stride = 1.0f + 0.5f * run; |
| 111 | if (!inspect) pose.aimPitch = camera.pitch; | 158 | if (!inspect) pose.aimPitch = camera.pitch; |
| 159 | // 空中の姿勢へなめらかに(着地で戻る) / blend into the airborne pose (and back on landing) | ||
| 160 | pose.air += ((body.grounded ? 0.0f : 1.0f) - pose.air) * approach(12.0f, dt); | ||
| 161 | if (!body.grounded) pose.walkAmount *= 1.0f - pose.air; | ||
| 112 | 162 | ||
| 113 | // 4. カメラ:CameraPivotソケットを追う / 4. the camera follows the CameraPivot socket | 163 | // 5. カメラ:CameraPivotソケットを追う / 5. the camera follows the CameraPivot socket |
| 114 | // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls) | 164 | // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls) |
| 115 | camera.update(cameraPivot(), cameraCollision ? std::span<const Aabb>(g.level.solids) : std::span<const Aabb>(), dt); | 165 | camera.update(cameraPivot(), cameraCollision ? std::span<const Aabb>(g.level.solids) : std::span<const Aabb>(), dt); |
| 116 | } | 166 | } |
| @@ -142,7 +192,19 @@ void PlayScene::drawDebugBoxes() { | |||
| 142 | s.set("uModel", translate(b.centre()) * scale(b.hi - b.lo)); | 192 | s.set("uModel", translate(b.centre()) * scale(b.hi - b.lo)); |
| 143 | g.renderer.cube.draw(); | 193 | g.renderer.cube.draw(); |
| 144 | } | 194 | } |
| 195 | // プレイヤーのカプセル(伸ばした球で近似して線で) / the player's capsule (approximated by a stretched sphere, as lines) | ||
| 196 | Vec3 feet = lerp(prevPosition, position, drawAlpha); | ||
| 197 | s.set("uColor", body.grounded ? Vec3{1.5f, 1.5f, 0.2f} : Vec3{2.0f, 0.4f, 0.1f}); | ||
| 198 | s.set("uModel", translate(feet + Vec3{0.0f, 0.5f * body.height, 0.0f}) * | ||
| 199 | scale({2.0f * body.radius, body.height, 2.0f * body.radius})); | ||
| 200 | g.renderer.sphere.draw(); | ||
| 145 | glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); | 201 | glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); |
| 202 | // 足元の軌跡:壁ずりでは壁に沿って曲がる / the trail of the feet: with wall sliding it bends along the wall | ||
| 203 | s.set("uColor", body.slide ? Vec3{0.2f, 1.6f, 2.0f} : Vec3{2.0f, 0.3f, 0.3f}); | ||
| 204 | for (int i = 0; i < trailCount; ++i) { | ||
| 205 | s.set("uModel", translate(trail[i] + Vec3{0.0f, 0.06f, 0.0f}) * scale({0.12f, 0.12f, 0.12f})); | ||
| 206 | g.renderer.cube.draw(); | ||
| 207 | } | ||
| 146 | // ソケット(空のノード)を小さな箱で、体に隠れないように深度テストなしで:CameraPivot 水色、Weapon 紫、 | 208 | // ソケット(空のノード)を小さな箱で、体に隠れないように深度テストなしで:CameraPivot 水色、Weapon 紫、 |
| 147 | // 両手 黄色、Muzzle 赤 | 209 | // 両手 黄色、Muzzle 赤 |
| 148 | // The sockets (empty nodes) as small boxes, without the depth test so the body does not hide them: CameraPivot | 210 | // The sockets (empty nodes) as small boxes, without the depth test so the body does not hide them: CameraPivot |
| @@ -172,6 +234,13 @@ void PlayScene::draw(float alpha) { | |||
| 172 | view.eye = lerp(prevEye, camera.eye(), alpha); | 234 | view.eye = lerp(prevEye, camera.eye(), alpha); |
| 173 | view.forward = normalize(lerp(prevForward, camera.forward(), alpha)); | 235 | view.forward = normalize(lerp(prevForward, camera.forward(), alpha)); |
| 174 | view.fovY = camera.fovY; | 236 | view.fovY = camera.fovY; |
| 237 | if (overhead) { | ||
| 238 | // O:上から見下ろすデバッグ用のカメラ(遊ぶカメラはそのまま動き続ける) / O: a debug camera looking down from above | ||
| 239 | // (the gameplay camera keeps working underneath) | ||
| 240 | Vec3 target = lerp(prevPosition, position, alpha); | ||
| 241 | view.eye = target + Vec3{0.0f, 11.0f, 6.0f}; | ||
| 242 | view.forward = normalize(target - view.eye); | ||
| 243 | } | ||
| 175 | view.aspect = static_cast<float>(g.window.width()) / static_cast<float>(g.window.height()); | 244 | view.aspect = static_cast<float>(g.window.width()) / static_cast<float>(g.window.height()); |
| 176 | view.time = time; | 245 | view.time = time; |
| 177 | 246 | ||
| @@ -224,16 +293,21 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 224 | std::string lines = std::format( | 293 | std::string lines = std::format( |
| 225 | "CPU frame {:.1f} ms (wall clock) llvmpipe raster: shadow {:.1f} ms, scene {:.1f} ms, post {:.1f} ms\n" | 294 | "CPU frame {:.1f} ms (wall clock) llvmpipe raster: shadow {:.1f} ms, scene {:.1f} ms, post {:.1f} ms\n" |
| 226 | "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" | 295 | "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" |
| 227 | "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M", | 296 | "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" |
| 297 | "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}", | ||
| 228 | g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, | 298 | g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, |
| 229 | levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), | 299 | levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), |
| 230 | camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", | 300 | camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", |
| 231 | cameraCollision ? "" : " (camera collision OFF)", g.level.solids.size(), culling ? "on" : "OFF (F4)", | 301 | cameraCollision ? "" : " (camera collision OFF)", g.level.solids.size(), culling ? "on" : "OFF (F4)", |
| 232 | static_cast<double>(r.timings.sceneFragments) / 1e6); | 302 | static_cast<double>(r.timings.sceneFragments) / 1e6, body.grounded ? "grounded" : "airborne", |
| 233 | batch.drawRect({0.0f, 0.0f, 1280.0f, 68.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); | 303 | body.hitWall ? "wall " : "", body.steppedUp ? "stepped-up " : "", body.snappedDown ? "snapped-down " : "", |
| 304 | body.contacts, body.position.y, body.velocity.x, body.velocity.y, body.velocity.z, jumps, | ||
| 305 | body.slide ? "on" : "OFF (L)"); | ||
| 306 | batch.drawRect({0.0f, 0.0f, 1280.0f, 88.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); | ||
| 234 | g.ui.draw(batch, lines, {10.0f, 6.0f}, small); | 307 | g.ui.draw(batch, lines, {10.0f, 6.0f}, small); |
| 235 | } | 308 | } |
| 236 | g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Q 肩 / shoulder B 箱 / boxes F3", | 309 | g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Space 跳ぶ / jump Q 肩 / shoulder " |
| 310 | "B 箱 / boxes F3", | ||
| 237 | {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre, | 311 | {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre, |
| 238 | .shadow = {0.0f, 0.0f, 0.0f, 0.8f}}); | 312 | .shadow = {0.0f, 0.0f, 0.0f, 0.8f}}); |
| 239 | batch.end(); | 313 | batch.end(); |
ファイル: a/games/tps/src/play_scene.hh | b/games/tps/src/play_scene.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -3,6 +3,7 @@ | |||
| 3 | // follows without entering walls | 3 | // follows without entering walls |
| 4 | #pragma once | 4 | #pragma once |
| 5 | 5 | ||
| 6 | #include "character_body.hh" | ||
| 6 | #include "game.hh" | 7 | #include "game.hh" |
| 7 | #include "third_person_camera.hh" | 8 | #include "third_person_camera.hh" |
| 8 | 9 | ||
| @@ -28,9 +29,15 @@ private: | |||
| 28 | ThirdPersonCamera camera; | 29 | ThirdPersonCamera camera; |
| 29 | Vec3 prevEye, prevForward; // 前のステップのカメラ(補間用) / last step's camera (for interpolation) | 30 | Vec3 prevEye, prevForward; // 前のステップのカメラ(補間用) / last step's camera (for interpolation) |
| 30 | 31 | ||
| 31 | // プレイヤー(第37章で当たり判定と重力が付く) / the player (chapter 37 adds collision and gravity) | 32 | // プレイヤー:体(カプセル、当たり判定、重力)と、描くための位置 / the player: the body (capsule, collision, |
| 33 | // gravity) and the positions drawing interpolates | ||
| 34 | CharacterBody body; | ||
| 32 | Vec3 position, prevPosition; | 35 | Vec3 position, prevPosition; |
| 33 | Vec3 velocity; | 36 | float coyote = 0.0f, jumpBuffer = 0.0f; |
| 37 | int jumps = 0; | ||
| 38 | static constexpr int kTrail = 80; // 軌跡(B):4秒分 / the trail (B): 4 seconds | ||
| 39 | Vec3 trail[kTrail]; | ||
| 40 | int trailNext = 0, trailCount = 0, trailTick = 0; | ||
| 34 | float heading = 0.0f, prevHeading = 0.0f; // カメラのyawと同じ決まり / same convention as the camera yaw | 41 | float heading = 0.0f, prevHeading = 0.0f; // カメラのyawと同じ決まり / same convention as the camera yaw |
| 35 | CharacterPose pose; | 42 | CharacterPose pose; |
| 36 | float time = 0.0f; | 43 | float time = 0.0f; |
| @@ -38,6 +45,7 @@ private: | |||
| 38 | // the character from the front) | 45 | // the character from the front) |
| 39 | bool cameraCollision = true; // K:カメラの当たり判定 / camera collision | 46 | bool cameraCollision = true; // K:カメラの当たり判定 / camera collision |
| 40 | bool culling = true; // F4:視錐台カリング / frustum culling | 47 | bool culling = true; // F4:視錐台カリング / frustum culling |
| 48 | bool overhead = false; // O:上からの視点 / view from above | ||
| 41 | bool posing = true; // P:手続き的な姿勢 / procedural pose | 49 | bool posing = true; // P:手続き的な姿勢 / procedural pose |
| 42 | float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor | 50 | float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor |
| 43 | LevelDrawStats levelStats, shadowStats; | 51 | LevelDrawStats levelStats, shadowStats; |
ファイル: a/games/tps/src/renderer.cc | b/games/tps/src/renderer.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -69,6 +69,7 @@ std::unique_ptr<Renderer> Renderer::create(int width, int height, const RenderSe | |||
| 69 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; | 69 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; |
| 70 | r->white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); | 70 | r->white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); |
| 71 | r->cube = makeCube(); | 71 | r->cube = makeCube(); |
| 72 | r->sphere = makeSphere(16, 8); | ||
| 72 | return r; | 73 | return r; |
| 73 | } | 74 | } |
| 74 | 75 | ||
ファイル: a/games/tps/src/renderer.hh | b/games/tps/src/renderer.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -119,6 +119,7 @@ public: | |||
| 119 | std::optional<Shader> unlit; // 光らない一色(デバッグの箱) / unlit color (debug boxes) | 119 | std::optional<Shader> unlit; // 光らない一色(デバッグの箱) / unlit color (debug boxes) |
| 120 | Texture2D white; | 120 | Texture2D white; |
| 121 | Mesh cube; // 1 × 1 × 1、中心が原点 / centered unit cube | 121 | Mesh cube; // 1 × 1 × 1、中心が原点 / centered unit cube |
| 122 | Mesh sphere; // 直径1、中心が原点 / diameter 1, centered | ||
| 122 | 123 | ||
| 123 | RenderSettings settings; | 124 | RenderSettings settings; |
| 124 | RenderTimings timings; // 数フレーム遅れの値 / values a few frames old | 125 | RenderTimings timings; // 数フレーム遅れの値 / values a few frames old |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。