XNA按住并单击同一对象

本文关键字:对象 单击 XNA | 更新日期: 2023-09-27 18:24:03

如果游戏中的同一个对象有两个不同的动作来点击它和按住鼠标,使用默认输入(当前和最后一个鼠标状态),即使按住也会激活点击动作。例如,您可以使用按住键在屏幕上拖放一个对象,但当您单击它时,它应该会消失。当你点击对象移动它的那一刻,它就会消失,这是一个不想要的结果。

MouseState current, last;
public void Update(GameTime gameTime) {
   current = Mouse.GetState();
   bool clicked = current.LeftButton == ButtonState.Pressed && last.LeftButton == ButtonState.Released;
   bool holding = current.LeftButton == ButtonState.Pressed;
   if(clicked) vanishObject();
   if(holding) moveObject(current.X, current.Y);
   last = current;
}

我想用一个"保持N秒以上"的标志来解决这个问题,并将消失放在ReleasedClick上,检查标志,但改变事件时间似乎不是一个优雅的解决方案。有什么想法吗?

XNA按住并单击同一对象

您正在考虑单击错误的方式。实现此行为的最简单方法是,仅当鼠标状态在上一帧被按下并在本帧被释放,并且尚未达到特定时间时,才触发Clicked操作。代码中:

private const float HOLD_TIMESPAN = .5f; //must hold down mouse for 1/2 sec to activate hold
MouseState current, last;
private float holdTimer;
public virtual void Update(GameTime gameTime)
{
    bool isHeld, isClicked; //start off with some flags, both false
    last = current; //store previous frame's mouse state
    current = Mouse.GetState(); //store this frame's mouse state
    if (current.LeftButton == ButtonState.Pressed)
    {
        holdTimer += (float)gameTime.ElapsedTime.TotalSeconds();
    }
    if (holdTimer > HOLD_TIMESPAN)
        isHeld = true;
    if (current.LeftButton == ButtonState.Released)
    {
        if (isHeld) //if we're releasing a held button
        {
            holdTimer = 0f; //reset the hold timer
            isHeld = false;
            OnHoldRelease(); //do anything you need to do when a held button is released
        }
        else if (last.LeftButton == ButtonState.Pressed) //if NOT held (i.e. we have not elapsed enough time for it to be a held button) and just released this frame
        {
            //this is a click
            isClicked = true;
        }
     }
     if (isClicked) VanishObject();
     else if (isHeld) MoveObject(current.X, current.Y);
 }

当然,这段代码还有一些优化的空间,但我认为这已经足够明智了。

您应该只更改用于消失对象的逻辑。你真正想要的是

if (clicked && !holding) vanishObject();

这应该是得到你想要的东西的最简单的方法。

   const float DragTimeLapsus = 0.2f;
   if (current.LeftButton == ButtonState.Released) time = 0;
   else time+= ElapsedSeconds;
   bool clicked = current.LeftButton == ButtonState.Released
               && last.LeftButton == ButtonState.Pressed 
               && time<DragTimeLapsus;
   bool holding = current.LeftButton == ButtonState.Pressed 
               && last.LeftButton == ButtonState.Pressed 
               && time>DragTimeLapsus ;