プレイヤーと当たったボールが飛んでいく
実装イメージ
・プレイヤーと当たったらボールが飛んでいきます。
・ボールの移動する方向はプレイヤー座標からボール座標の方向です。
・ボールは徐々にゆっくりになっていきます。
サンプルプログラム
#include "DxLib.h"
#include <math.h>
// プレイヤー円の半径
#define PLAYER_RADIUS 35.0f
// ボールの半径
#define BALL_RADIUS 15.0f
// プレイヤー画像ハンドル
int PlayerGraph;
// プレイヤー座標
float PlayerX;
float PlayerY;
// ボール画像ハンドル
int BallGraph;
// ボール座標
float BallPosX;
float BallPosY;
// ボール移動量
float BallMovX;
float BallMovY;
// ==============================
// *** 初期化処理 ***
// ==============================
void Game_Init()
{
// 画像の読み込み
PlayerGraph = LoadGraph( "プレイヤー.png" );
BallGraph = LoadGraph( "ボール.png" );
PlayerX = 50.0f;
PlayerY = 100.0f;
BallPosX = 150.0f;
BallPosY = 100.0f;
BallMovX = 0.0f;
BallMovY = 0.0f;
}
// ==============================
// *** 更新処理 ***
// ==============================
void Game_Update()
{
// 十字キーでプレイヤー移動
if( CheckHitKey( KEY_INPUT_RIGHT ) ) PlayerX += 2.0f;
if( CheckHitKey( KEY_INPUT_LEFT ) ) PlayerX -= 2.0f;
if( CheckHitKey( KEY_INPUT_DOWN ) ) PlayerY += 2.0f;
if( CheckHitKey( KEY_INPUT_UP ) ) PlayerY -= 2.0f;
// ボールからプレイヤーまでの距離を計算
float x = BallPosX - PlayerX;
float y = BallPosY - PlayerY;
float length = sqrtf( x * x + y * y );
// 半径の合計よりも短かったら
if( length < PLAYER_RADIUS + BALL_RADIUS ){
// 大きさを 10.0f にして移動量設定
BallMovX = x / length * 10.0f;
BallMovY = y / length * 10.0f;
}
// 移動ベクトルを短くして
BallMovX *= 0.9f;
BallMovY *= 0.9f;
// 座標を進める
BallPosX += BallMovX;
BallPosY += BallMovY;
}
// ==============================
// *** 描画処理 ***
// ==============================
void Game_Draw()
{
// プレイヤーの描画
DrawRotaGraphF( PlayerX, PlayerY, 1.0f, 0.0f, PlayerGraph, TRUE );
// プレイヤー円の描画
DrawCircle( PlayerX, PlayerY, PLAYER_RADIUS, GetColor( 255, 255, 255 ), FALSE );
// ボールの描画
DrawRotaGraphF( BallPosX, BallPosY, 1.0f, 0.0f, BallGraph, TRUE );
}
// ==============================
// *** 終了処理 ***
// ==============================
void Game_End()
{
DeleteGraph( PlayerGraph );
DeleteGraph( BallGraph );
}
// ******************************
// メイン関数
// ******************************
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;
}