我正在使用C#和MonoGame制作游戏,需要检测何时按下特定键。我创建了一个控制器类,它按照以下方式检测换档键按下(使玩家射击子弹的按钮)。
public class Controller
{
KeyboardState keyboardState;
public Controller()
{
}
public void Update()
{
keyboardState = Keyboard.GetState(); //Get a new controller state
}
public bool RightShootButton
{
get
{
return keyboardState.IsKeyDown(Keys.RightShift); //Shoot a bullet to the right if right shift is pressed
}
}
public bool LeftShootButton
{
get
{
return keyboardState.IsKeyDown(Keys.LeftShift); //Shoot a bullet to the left if left shift is pressed
}
}
}
RightShootButton属性工作正常,但LeftShootButton有一个奇怪的故障。当按下任何箭头键(向上,向下,向左或向右)时,玩家向左射击子弹,即使我没有要求按键。 KeyboardState是否有可能错误地检测到按键,或者我的代码中是否存在我错过的错误?如果是前者,有什么方法可以解决这个问题吗?
编辑:
这里有一些代码来展示工作原理。子弹是在Player类中这样创建的。这是创建项目符号的唯一代码部分(它们被添加到列表中)。
if (controller.RightShootButton)
{
level.Bullets.Add(new Bullet(playerPosition, true)); //These parameters define where the bullet is and whether it travels left or right
}
else if (controller.LeftShootButton)
{
level.Bullets.Add(new Bullet(playerPosition, false));
}
玩家使用此代码左右移动。同样,这是涉及移动的代码的唯一部分。
if (controller.RightButton || controller.LeftButton)
{
if (controller.RightButton && playerPosition.X < level.End)
{
playerPosition.X += 2; //Move right if the player hasn't reached the side of the screen (the level.End value)
}
if (controller.LeftButton && playerPosition.X > 0)
{
playerPosition.X -= 2; //Move left if not at the side of the screen
}
}
最后,这些是检测控制器类中箭头键按下的属性。这些目前有游戏手柄功能,但拍摄属性没有。
public bool UpButton
{
get
{
return keyboardState.IsKeyDown(Keys.Up) || gamepadState.DPad.Up == ButtonState.Pressed || gamepadState.ThumbSticks.Left.Y > 0.0f;
}
}
public bool DownButton
{
get
{
return keyboardState.IsKeyDown(Keys.Down) || gamepadState.DPad.Down == ButtonState.Pressed || gamepadState.ThumbSticks.Left.Y < 0.0f;
}
}
public bool LeftButton
{
get
{
return keyboardState.IsKeyDown(Keys.Left) || gamepadState.DPad.Left == ButtonState.Pressed || gamepadState.ThumbSticks.Left.X < 0.0f;
}
}
public bool RightButton
{
get
{
return keyboardState.IsKeyDown(Keys.Right) || gamepadState.DPad.Right == ButtonState.Pressed || gamepadState.ThumbSticks.Left.X > 0.0f;
}
}