2012-02-11 14 views
0

ゲームの同じオブジェクトに2つの異なるアクションがあり、マウスをクリックしてクリックすると、デフォルトの入力(現在と最後のMouseState)を使用して、あなたが持っているときでさえ、クリックアクション。たとえば、ホールドを使用してオブジェクトを画面上にドラッグアンドドロップしますが、クリックすると消えます。移動するオブジェクトをクリックするとすぐに消えてしまい、望ましくない結果になります。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イベントではなく、Releaseイベントのクリックを達成するために事実を変更した人はいません。 – Mephy

答えて

0

オブジェクトを無効にするロジックを変更するだけです。あなたが本当に望んでいるのは

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

あなたが望むものを得るための最も簡単な方法です。

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

もちろん、このコードの最適化の余地はありますが、十分に分かりやすいと思います。

+0

realeaseがクリックと同じ位置にあった場合はマウスの位置を確認する方が良いと思う、クリックされた、それ以外はドラッグされた –

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 ; 
関連する問題