我目前正在从事单人游戏。游戏很大程度上取决于单击按钮,而这就是问题所在。每当我按住鼠标左键,然后将其移动到游戏中的某个按钮上方时,该按钮都会立即被单击。
我试图通过多种方式来解决该问题,方法是以不同的方式重新排列if语句,添加一个额外的bool来检查是否单击了鼠标按钮,等等。但是没有任何运气。在任何地方都没有找到任何解决方案。
public override void Update(GameTime gameTime)
{
MouseState state = Mouse.GetState();
if (new Rectangle((position - ElementCenter).ToPoint(), sprite.Bounds.Size)
.Contains(state.Position) && oldState.LeftButton == ButtonState.Released)
{
renderColor = Color.LightSlateGray;
if (state.LeftButton == ButtonState.Pressed &&
oldState.LeftButton == ButtonState.Released)
{
switch (button)
{
case "UI/submit":
if (GameWorld.Instance.Team.UserTeamName.Length > 0)
{
GameWorld.Instance.SubmitTeamName();
}
break;
case "UI/teammanager":
GameWorld.Instance.TeamManager();
break;
default:
break;
}
}
}
else
{
renderColor = Color.White;
}
oldState = state;
}
理想情况下,我希望仅当在单击按钮之前释放鼠标左键时才单击按钮。
答案 0 :(得分:3)
如果将oldState
声明为实例字段,则该类的不同实例将具有不同的版本。也就是说,旧的状态可能会迷路。
将oldState
声明为static
!
private static MouseState oldState = Mouse.GetState();
答案 1 :(得分:0)
我通常使用这样的类来读取输入
public class InputManager
{
KeyboardState currentKeyboard, previousKeyboard;
MouseState currentMouse, previousMouse;
public bool LeftKeyIsHeldDown { get; private set; }
public bool RightKeyIsHeldDown { get; private set; }
public bool JumpWasJustPressed { get; private set; }
public bool FireWasJustPressed { get; private set; }
public void Update()
{
previousKeyboard = currentKeyboard;
currentKeyboard = Keyboard.GetState();
previousMouse = currentMouse;
currentMouse = Mouse.GetState();
LeftKeyIsHeldDown = currentKeyboard.IsKeyDown(Keys.A);
RightKeyIsHeldDown = currentKeyboard.IsKeyDown(Keys.D);
JumpWasJustPressed = currentKeyboard.IsKeyDown(Keys.Space) && previousKeyboard.IsKeyUp(Keys.Space);
FireWasJustPressed = currentMouse.LeftButton == ButtonState.Pressed && previousMouse.LeftButton == ButtonState.Released;
}
}