ほとんどのゲームはイベントを待ちません。必要に応じて入力デバイスをポーリングし、それに応じて動作します。実際、XNA を見てみると、更新ルーチンで呼び出す Keyboard.GetState() メソッド (または Gamepad.GetState()) があり、それに基づいてゲーム ロジックを更新することがわかります。結果。Windows.Forms を使用する場合、すぐに使用できるものはありませんが、GetKeyBoardState() 関数を P/Invoke してこれを利用することができます。これの良いところは、一度に複数のキーをポーリングできるため、一度に複数のキーの押下に反応できることです。これに役立つオンラインで見つけた簡単なクラスを次に示します。
http://sanity-free.org/17/obtaining_key_state_info_in_dotnet_csharp_getkeystate_implementation.html
実演するために、基本的にキーボード入力に基づいてボールを動かす単純な Windows アプリを作成しました。リンクしたクラスを使用して、キーボードの状態をポーリングします。一度に 2 つのキーを押したままにすると、斜めに移動します。
まず、Ball.cs:
public class Ball
{
private Brush brush;
public float X { get; set; }
public float Y { get; set; }
public float DX { get; set; }
public float DY { get; set; }
public Color Color { get; set; }
public float Size { get; set; }
public void Draw(Graphics g)
{
if (this.brush == null)
{
this.brush = new SolidBrush(this.Color);
}
g.FillEllipse(this.brush, X, Y, Size, Size);
}
public void MoveRight()
{
this.X += DX;
}
public void MoveLeft()
{
this.X -= this.DX;
}
public void MoveUp()
{
this.Y -= this.DY;
}
public void MoveDown()
{
this.Y += this.DY;
}
}
本当に何の変哲もない……。
Form1 のコードは次のとおりです。
public partial class Form1 : Form
{
private Ball ball;
private Timer timer;
public Form1()
{
InitializeComponent();
this.ball = new Ball
{
X = 10f,
Y = 10f,
DX = 2f,
DY = 2f,
Color = Color.Red,
Size = 10f
};
this.timer = new Timer();
timer.Interval = 20;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
var left = KeyboardInfo.GetKeyState(Keys.Left);
var right = KeyboardInfo.GetKeyState(Keys.Right);
var up = KeyboardInfo.GetKeyState(Keys.Up);
var down = KeyboardInfo.GetKeyState(Keys.Down);
if (left.IsPressed)
{
ball.MoveLeft();
this.Invalidate();
}
if (right.IsPressed)
{
ball.MoveRight();
this.Invalidate();
}
if (up.IsPressed)
{
ball.MoveUp();
this.Invalidate();
}
if (down.IsPressed)
{
ball.MoveDown();
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (this.ball != null)
{
this.ball.Draw(e.Graphics);
}
}
}
シンプルな小さなアプリ。ボールとタイマーを作成するだけです。20 ミリ秒ごとにキーボードの状態をチェックし、キーが押された場合はキーを移動して無効にし、再描画できるようにします。