ゲームプログラム・サンプルプログラム集 (トップページに戻る)
マウス座標に一番近いプレイヤーにカーソル
実装イメージ

・マウスに一番近いプレイヤーの座標にカーソルを表示しています。
サンプルプログラム

#include "DxLib.h"
#include <math.h>

// プレイヤー数
#define MAX_PLAYER	5
// プレイヤー画像ハンドル
int PlayerGraph;
// プレイヤー座標
float PlayerX[MAX_PLAYER];
float PlayerY[MAX_PLAYER];

// カーソル画像用ハンドル
int CursorHandle;
// カーソル座標
float CursorX;
float CursorY;

// ==============================
// *** 初期化処理 ***
// ==============================
void Game_Init()
{
	// プレイヤー画像の読み込み
	PlayerGraph = LoadGraph( "プレイヤー.png" );
	// カーソル画像を読み込む
	CursorHandle = LoadGraph( "カーソル.png" );

	// 初期設定
	for( int i = 0; i < MAX_PLAYER; i++ ){
		PlayerX[i] = GetRand( 500 );
		PlayerY[i] = GetRand( 200 );
	}
}
// ==============================
// *** 更新処理 ***
// ==============================
void Game_Update()
{
	int MouseX, MouseY;
	// マウスの位置を取得
	GetMousePoint( &MouseX, &MouseY );
	// 近い距離を入れる
	float NearLength = 1000.0f;
	// その時のプレイヤー番号
	int NearNum = 0;

	for( int i = 0; i < MAX_PLAYER; i++ ){
		float x = PlayerX[i] - MouseX;
		float y = PlayerY[i] - MouseY;
		// マウスからプレイヤーまでの距離を計算
		float length = sqrtf( x * x + y * y );
		// 今の距離よりも短かったら
		if( NearLength > length ){
			// 距離を入れなおして
			NearLength = length;
			// 番号を設定
			NearNum = i;
		}
	}
	// 一番近い番号のプレイヤー座標にする
	CursorX = PlayerX[NearNum];
	CursorY = PlayerY[NearNum];
}
// ==============================
// *** 描画処理 ***
// ==============================
void Game_Draw()
{
	// プレイヤーの描画(特に移動していません)
	for( int i = 0; i < MAX_PLAYER; i++ ){
		DrawRotaGraphF( PlayerX[i], PlayerY[i], 1.0f, 0.0f, PlayerGraph, TRUE );
	}
	// カーソル画像の描画
	DrawRotaGraphF( CursorX, CursorY, 1.0f, 0.0f, CursorHandle, TRUE );
}
// ==============================
// *** 終了処理 ***
// ==============================
void Game_End()
{
	DeleteGraph( PlayerGraph );
	DeleteGraph( CursorHandle );
}

// ******************************
// メイン関数
// ******************************
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	ChangeWindowMode( TRUE );
	SetGraphMode( 500, 200, 16 );
	if( DxLib_Init() == -1 ){
		return -1;
	}
	SetDrawScreen( DX_SCREEN_BACK );

	Game_Init();		// *** 初期化処理 ***

	while( ProcessMessage() == 0 && CheckHitKey( KEY_INPUT_ESCAPE ) == 0 ){
		Game_Update();	// *** 更新処理 ***

		ClearDrawScreen();
		Game_Draw();	// *** 描画処理 ***
		ScreenFlip();
	}

	Game_End();			// *** 終了処理 ***
	DxLib_End();
	return 0;
}