第3章 画像の表示・動作

3-6 キャラクタ同士の衝突を調べるには?(当たり判定・2)

一般的に2Dのゲームでキャラクタ同士の当たり判定を検出する場合、長方形が用いられる。では、2つの長方形の重なり(衝突)のパターンにはどのようなものがあるだろうか。

これらのパターンをそれぞれ調べていたのでは面倒なので、上記3パターンを満たす簡単な判定方法を紹介する。

キャラクタの表示座標をx,yで持っている場合の当たり判定を考える。

(a) RECT構造体を使わない

キャラクタ画像の矩形を元に幅と高さを求め、当たり判定に利用する。

// データの準備
a_width = aRect.right - aRect.left;
a_height = aRect.bottom - aRect.top;
b_width = bRect.right - bRect.left;
b_height = bRect.bottom - bRect.top;
// 当たり判定
if (a_x <= (b_x + b_width) && a_y <= (b_y + b_height) && (a_x + a_width) >= b_x && (a_y + a_height) >= b_y)

(b) RECT構造体を使う

キャラクタ画像の矩形とx,y座標を元に左上右下座標データを作成し、当たり判定に利用する。

// データの準備
a_width = aRect.right - aRect.left;
a_height = aRect.bottom - aRect.top;
SetRect(&a, a_x, a_y, a_x + a_width, a_y + a_height);
b_width = bRect.right - bRect.left;
b_height = bRect.bottom - bRect.top;
SetRect(&b, b_x, b_y, b_x + b_width, b_y + b_height);
// 当たり判定
if (a.left <= b.right && a.top <= b.bottom && a.right >= b.left && a.bottom >= b.top)

(c) 実際のプログラム

実際のプログラムでは、当たり判定はよく使うので、関数化しておくとよい。

//-----------------------------------------------------------------------------
// 関数名 : HitCheck()
// 機能概要: あたり判定関数
//-----------------------------------------------------------------------------
bool HitCheck(RECT Rect1, RECT Rect2)
{
    if (Rect1.left <= Rect2.right &&
        Rect1.top <= Rect2.bottom &&
        Rect1.right >= Rect2.left &&
        Rect1.bottom >= Rect2.top)
        return true;
    else
        return false;

}

RECTデータを求める処理も関数化して、自動的に求められるようにすると、GOOD。


[ TOP ] [ Next ]