【问题标题】:Joystick acquisition with SharpDX使用 SharpDX 进行操纵杆采集
【发布时间】:2013-08-24 07:12:35
【问题描述】:

我是 C# 和 Sharpdx 的新手。几天前我遇到了这个代码问题,我不明白方法不起作用!这是一项简单的任务,即获取操纵杆的一个轴的值​​并将其显示在表单中的文本框上。

我在 Visual Studio 2010 express 上做了一个新项目,我做了一个带有按钮和文本框的表单,用于显示操纵杆轴(X 轴)的值。

这里的第一部分代码是Sharpdx文档中的示例,第二部分有点不同。

问题是每次按下按钮时值都不会改变

出了点问题,但我不知道是什么

private void button3_Click(object sender, EventArgs e)
{
  // Initialize DirectInput
  var directInput = new DirectInput();

  // Find a Joystick Guid
  var joystickGuid = Guid.Empty;

  foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,  DeviceEnumerationFlags.AllDevices))
    joystickGuid = deviceInstance.InstanceGuid;

  // If Gamepad not found, look for a Joystick
  if (joystickGuid == Guid.Empty)
    foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,  DeviceEnumerationFlags.AllDevices))
      joystickGuid = deviceInstance.InstanceGuid;

  // If Joystick not found, throws an error
  if (joystickGuid == Guid.Empty)
  {
      Console.WriteLine("No joystick/Gamepad found.");
      Console.ReadKey();
      Environment.Exit(1);
  }  

  // Instantiate the joystick e stato
  Joystick joystick = new Joystick(directInput, joystickGuid);
  JoystickState stato = new JoystickState();

  // specifico se relativo o assoluto
  joystick.Properties.AxisMode = DeviceAxisMode.Absolute;

  // effettuo un collegamento con il joystick
  joystick.Acquire();

  // qui faccio una acquisizione dello stato che memorizzo
  joystick.Poll();

  // effettuo una lettura dello stato
  joystick.GetCurrentState(ref stato);

  // stampo il valore dell'ordinata
  textBox1.Text = stato.X.ToString();
}

【问题讨论】:

    标签: c# joystick sharpdx


    【解决方案1】:

    我认为问题在于您同时调用 PollGetCurrentState - 您只需要做一个或另一个。

    从您的问题来看,这听起来像是后者-也就是说,您想在按下按钮时GetCurrentState-而不是Poll 进行循环更改。

    如果您确实想获得当前状态,那么您需要这样的东西。

    var directInput = new DirectInput();
    var joystickState = new JoystickState();
    var joystick = new Joystick(directInput, joystickGuid);
    joystick.Acquire();
    joystick.GetCurrentState(ref joystickState);
    textBox1.Text = joystickState.X.ToString();
    

    如果您想轮询更改,您需要这样的东西。

    var directInput = new DirectInput();
    var joystick = new Joystick(directInput, joystickGuid);
    joystick.Acquire();
    joystick.Properties.BufferSize = 128;
    while (true)
    {
      joystick.Poll();
      var data = joystick.GetBufferedData();
      foreach (var state in data) 
      {
        if (state.Offset == JoystickOffset.X)
        {
           textBox1.Text = state.Value;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多