2012-02-11 19 views
0

如果在一場比賽中同一個對象有點擊它並按住鼠標點擊了它,使用默認輸入(當前和最後MouseState)兩個不同的動作,你就會激活即使在您持有的情況下也可以點擊操作例如,您使用該按鈕拖動n'將一個對象拖放到屏幕上,但是當您單擊它時,它應該消失。當你點擊物體移動它時,它會消失,這是一個不想要的結果。XNA保持和點擊同一對象上

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的消失,檢查標誌,但改變事件時間似乎並沒有成爲一個優雅的解決方案。有任何想法嗎?

+0

感謝大家回答我,但沒有人改變了事實,以實現點擊發布事件,而不是Press。 – Mephy 2012-02-15 16:13:25

回答

0

您應該改變消除對象的邏輯。你真正想要的是

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

這應該是獲得你想要的最簡單的方法。

0

你在想點擊走錯了路。實現這種行爲的最簡單方法是,只有當mouseState被按下最後一幀並且釋放該幀,並且如果沒有達到特定時間,才觸發點擊操作。代碼:

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); 
} 

當然這個代碼有一些優化的空間,但我認爲這是足夠明智的。

+0

我認爲它更好地檢查鼠標位置,如果釋放與點擊位置相同,則會被點擊,否則會被拖動 – 2015-08-17 14:22:16

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 ; 
相關問題