当たり判定のプログラム例 二つの円
二つの円の重なりを判定するプログラム例。DX ライブラリを使用。
プログラムの概要
矢印キーで白い円Aを動かします。画面中央に置かれた青い円Bに重ねると、Bの色が赤くなります。
ソースコード
#include "DxLib.h" #include <tchar.h> // 円を表すクラス class CCircle { TCHAR name[20]; // 名前 int mx; // 中心の x 座標 int my; // 中心の y 座標 int rd; // 半径 public: CCircle( LPCTSTR str ) { _tcscpy_s( name, sizeof(name)/sizeof(TCHAR), str ); mx = my = rd = 0; } // コンストラクタ void set( int x, int y, int r ) { mx = x; my = y; rd = r; } // 値をセットする int get_mx() const { return mx; } // mx の値を返す int get_my() const { return my; } // my の値を返す int get_rd() const { return rd; } // rd の値を返す void moveUp() { my--; } // 上へ移動 void moveDown() { my++; } // 下へ移動 void moveLeft() { mx--; } // 左へ移動 void moveRight() { mx++; } // 右へ移動 void displayInfo ( int x, int y, int colorCode ) const { DrawFormatString( x, y, colorCode, _T("%s: (mx, my) = (%3d, %3d), rd = %3d"), name, mx, my, rd ); } // 情報の表示 void draw( int colorCode ) const { DrawCircle( mx, my, rd, colorCode, TRUE ); } // 描画 BOOL isIntersected( const CCircle& b ) const { int dx = b.get_mx() - mx; int dy = b.get_my() - my; int r = b.get_rd() + rd; return ( dx*dx + dy*dy < r*r ); } // 交差しているかどうかの判定 }; int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { ChangeWindowMode( TRUE ); // フルスクリーンで起動しない SetGraphMode( 640, 480, 16 ); // 画面:640x480、カラー:16bit if( DxLib_Init() == -1 ) { return -1; } // DXライブラリ初期化 SetDrawScreen( DX_SCREEN_BACK ); // 描画先画面を裏画面にセット // 円の作成 CCircle circle_A( _T("A") ); circle_A.set( 160, 160, 60 ); CCircle circle_B( _T("B") ); circle_B.set( 320, 240, 100 ); // 色コードの取得 int col_red = GetColor( 255, 0, 0 ); int col_blue = GetColor( 64, 128, 255 ); int col_white = GetColor( 255, 255, 255 ); while( ProcessMessage() == 0 && CheckHitKey( KEY_INPUT_ESCAPE ) == 0 ) { ClearDrawScreen(); // 画面クリア // 円Aを矢印キーで動かす if( CheckHitKey( KEY_INPUT_UP ) ) { circle_A.moveUp(); } if( CheckHitKey( KEY_INPUT_DOWN ) ) { circle_A.moveDown(); } if( CheckHitKey( KEY_INPUT_LEFT ) ) { circle_A.moveLeft(); } if( CheckHitKey( KEY_INPUT_RIGHT ) ) { circle_A.moveRight(); } // 円Bの描画 if( circle_A.isIntersected( circle_B ) ) { circle_B.draw( col_red ); // 円が重なったら赤 } else { circle_B.draw( col_blue ); // 重ならなければ青 } // 円Aの描画 circle_A.draw( col_white ); // 円の情報を表示 circle_A.displayInfo( 4, 4, col_white ); circle_B.displayInfo( 4, 24, col_white ); ScreenFlip(); // 裏画面の内容を表画面に反映させる } DxLib_End(); // DXライブラリ使用の終了処理 return 0; // ソフトの終了 }