コントローラのボタンが押されているかどうかを検出する
#かなりいい加減な訳です
このサンプルではXbox360のボタンが押されているかどうかの判定を行う方法を示します。このサンプルでは、GamePadStateオブジェクトを記憶しておいて、Aボタンが離されている状態から押されている状態に変化したかどうかを判定します。もし変化してたら、ユーザはボタンを押したということです。
コントローラのボタンが押されたを判定する方法
1. GetState関数で、Xbox360コントローラの状態を調べる。
2. IsConnectedプロパティを見てコントローラがちゃんと刺さってるか確かめる。
3. 前回のPacketNumberプロパティを保存しておいて、PacketNumberプロパティが 前回から変化してるかを調べる。
4. 調べたいボタンの、前回の状態と今回のステータスを比較する。 もし、今回の状態が「押されている」で前回の状態が「離されている」だったら、 そのボタンは今まさに押されたということ。
5. 前回の状態を記録していた変数にを今回の状態を代入する。
#region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; #endregion public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; ContentManager content; public Game1() { graphics = new GraphicsDeviceManager(this); content = new ContentManager(Services); } protected override void Initialize() { base.Initialize(); } protected override void LoadGraphicsContent(bool loadAllContent) { if (loadAllContent) { } } protected override void UnloadGraphicsContent(bool unloadAllContent) { if (unloadAllContent == true) { content.Unload(); } } protected override void Update(GameTime gameTime) { // Allows the default game to exit on Xbox 360 and Windows if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); }
UpdateInput(); base.Update(gameTime); } GamePadState previousGamePadState; void UpdateInput() { //プレーヤ1の現在の状態をチェックする GamePadState currentState = GamePad.GetState(PlayerIndex.One); //コントローラが接続されていて、かつパケット数が異なっていたら処理を行う if ((currentState.IsConnected) && (currentState.PacketNumber != previousGamePadState.PacketNumber)) { if (currentState.Buttons.A == ButtonState.Pressed && previousGamePadState.Buttons.A == ButtonState.Released) { //Aボタンは今まさに押された GamePad.SetVibration(PlayerIndex.One, 1.0f, 1.0f); } else if (currentState.Buttons.A == ButtonState.Released && previousGamePadState.Buttons.A == ButtonState.Pressed) { //Aボタンは今離された GamePad.SetVibration(PlayerIndex.One, 0.0f, 0.0f); } //PreviousGamePadStateを更新する。 previousGamePadState = currentState; } } protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); base.Draw(gameTime); } }
See Also
How to: Detect Whether a Controller Is Disconnected
How to: Detect Whether a Controller Is Disconnected
affillogo.gif