2011-12-21 107 views
2

我想每次按下按鈕或移動操縱桿的軸時更新操縱桿狀態。我已經有這個代碼:如何更新操縱桿狀態

Imports Microsoft.DirectX 
Imports Microsoft.DirectX.DirectInput 

Dim js As Device = Nothing 

For Each DI As DeviceInstance In Manager.GetDevices(DeviceClass.GameControl, _ 
    EnumDevicesFlags.AttachedOnly) 

    js = New Device(DI.InstanceGuid) 
    Exit For 
Next 

If js Is Nothing Then 
    Throw New Exception("No joystick found") 
End If 

Dim wih As New System.Windows.Interop.WindowInteropHelper(Me) 
js.SetCooperativeLevel(wih.Handle, CooperativeLevelFlags.NonExclusive Or _ 
    CooperativeLevelFlags.Background) 
js.Acquire() 

Dim state As JoystickState = js.CurrentJoystickState 

最後一行獲取操縱桿的狀態。我已經看到,使用了一個計時器,每次滴答狀態刷新,但它似乎效率不高,因爲如果我不按任何按鈕狀態刷新無論如何。那麼如何才能在需要時刷新狀態?

+0

重要嗎?我假設它是每秒50或100次的順序 - 可能與幀頻相匹配? - 並且您沒有將昂貴的操作附加到更新上,那麼問題是什麼?這很可能是因爲操作系統沒有通知遊戲杆改變機制,所以代碼在某處被強制輪詢。 – Rup 2011-12-21 19:38:27

+0

@Rup如果我使用調度計時器,時間跨度應該多大? – Cobold 2011-12-21 19:57:12

+0

......哦,我明白了 - 我的誤解,對不起。我讀到'有DX提供的計時器,我想要更好的解決方案',而不是'我見過其他人使用計時器'。如果您確實需要輪詢 - 如果DirectInput設備沒有「register event notificaiton」 - 那麼您可以按照遊戲進程輸入的頻率進行輪詢,該頻率可以是vsync或在後臺world-update線程中我猜? – Rup 2011-12-21 20:04:36

回答

0

我發現了一些關於如何只在操縱桿狀態發生變化時更新操縱桿狀態的C#代碼。我看你已經有了:

Dim state As JoystickState = js.CurrentJoystickState 

也許嘗試只是類似於下面的例子中補充說:「這是C#」

  //Capture Position. 
      info += "X:" + state.X + " "; 
      info += "Y:" + state.Y + " "; 
      info += "Z:" + state.Z + " "; 

      //Capture Buttons. 
      byte[] buttons = state.GetButtons(); 
      for(int i = 0; i < buttons.Length; i++) 
      { 
       if(buttons[i] != 0) 
       { 
        info += "Button:" + i + " "; 
       } 
      } 

這裏是全段我發現這裏位於:https://msdn.microsoft.com/en-us/library/windows/desktop/bb153252%28v=vs.85%29.aspx#dx_DirectInput_capturing_device_objects

private void UpdateJoystick() 
    { 
     string info = "Joystick: "; 

     //Get Mouse State. 
     JoystickState state = joystick.CurrentJoystickState; 

     //Capture Position. 
     info += "X:" + state.X + " "; 
     info += "Y:" + state.Y + " "; 
     info += "Z:" + state.Z + " "; 

     //Capture Buttons. 
     byte[] buttons = state.GetButtons(); 
     for(int i = 0; i < buttons.Length; i++) 
     { 
      if(buttons[i] != 0) 
      { 
       info += "Button:" + i + " "; 
      } 
     } 

     lbJoystick.Text = info; 
    } 
+0

但是,這看起來像只是閱讀操縱桿的當前狀態,所以需要定期調用以輪詢遊戲桿狀態,而不是在遊戲桿狀態發生變化時檢測或通知它? – Rup 2015-03-31 14:28:51

+0

我認爲有人已經這樣說過,但爲什麼計時器計時器不夠用呢?僅僅因爲它不是DirectX中的實際定時器? – llooker 2015-03-31 16:47:28