ボールを動かすコード
タイマーを使いボールを動かす
ボールは、Timerコンポーネントを用いて一定間隔で移動させます。ツールパレットの「System」カテゴリから、TTimerコンポーネントをフォーム上に配置します。
| プロパティ | 値 |
|---|---|
| Enabled | False |
| Interval | 10 |
TTimerは、Intervalプロパティで指定した間隔(ミリ秒)で、OnTimerイベントを呼び出します。ここにボールを移動させるコードを記述します。
//Timer1のイベントハンドラ
void __fastcall TGameForm::Timer1Timer(TObject *Sender)
{
MoveBall();
}
//ボールを移動する関数コール
void __fastcall TGameForm::MoveBall()
{
// 移動後のボールの位置を計算します
int x = Ball->Position->X + FDeltaX;
int y = Ball->Position->Y + FDeltaY;
TPosition *pos = Racket->Position; // ラケットの座標
auto f1 = [this](const int inp, const int in_ang, String mp3name)->int
{
auto beep = beep_start(mp3name);
FAng = in_ang - FAng; // 跳ね返った角度を計算
CalcNewDelta(); // 新しい移動量を計算
if (beep != nullptr) {
beep->Play();
}
if (inp < 0){ return 0; };
return inp;
};
// ラケットにヒットしたかどうかを判定
if (CheckHit(Ball->Position->X, Ball->Position->Y, x, y, pos)) {
if (x < pos->X + 2 || x + Ball->Width > pos->X + Ball->Width - 2)
{
f1(0, 360, racket_mp3);
FAng += (Random(60) - 30); // 角で引っかけた
}
else
f1(0, 360, racket_mp3);
++Score;
Ball->Position->X = x;
Ball->Position->Y = y;
return;
}
//壁に当たったかの判定
if (y + Ball->Height >= Court->Height)
{
// 下の壁
Timer1->Enabled = false;
LostRacket( // ラケットを消す
[this]()
{
RacketCount--; // = RacketCount - 1;
if (RacketCount == 0)
{
GameOver(); // ゲームオーバー
}
else
{
// 次のラケットを使ったゲームの準備
FSpeed += 0.4;
Ball->Position->X = Court->Width / 2;
Ball->Position->Y = Court->Height / 3;
FAng = Random(45) + 90;
CalcNewDelta();
Timer1->Enabled = true;
}
});
return;
}
else if (y < 0)
{
// 上の壁
FSpeed += 0.1; // 上の壁に当たると少し早くなります
y = f1(y, 360, wall_mp3);
}
if (x + Ball->Width >= Court->Width)
{
// 右の壁
x = f1(Court->Width - Ball->Width, 182, wall_mp3);
}
else if (x < 0)
{
// 左の壁
x = f1(x, 182, wall_mp3);
}
// ボールの位置を変更
Ball->Position->X = x;
Ball->Position->Y = y;
}

