XNA保持并单击相同的对象

时间:2012-02-11 17:03:09

标签: c# xna mouse

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

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上,检查标志,但改变事件时间似乎不是一个优雅的解决方案。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

你应该改变你消失对象的逻辑。你真正想要的是

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

这应该是获得你想要的最简单的方法。

答案 1 :(得分:0)

你正在考虑点击错误的方式。实现此行为的最简单方法是,如果mouseState是按下最后一帧并释放此帧,并且尚未达到某个时间,则仅触发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);
 }

当然,这个代码有一些优化的空间,但我认为这是合理的。

答案 2 :(得分:0)

   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 ;