unity基础开发----unity获取外部设备(方向盘)按键

来源:互联网 发布:八岐大蛇 mac 蓝牙 编辑:程序博客网 时间:2024/05/09 09:51

在unity中可能会用到外部的设备,比如是游戏手柄,赛车的方向盘手柄,在unity中 input manger中最多可以获取到10个按键,但是就像赛车的游戏手柄可能在电脑pc上可以显示,但是在unity中就获取不到了。那我们只能用其他的方法来解决这个问题了。

using UnityEngine;using System.Collections;using System.Runtime.InteropServices;public class JoystickController : MonoBehaviour {public struct JOYINFOEX{/// <summary>/// Size, in bytes, of this structure./// </summary>public int dwSize;/// <summary>/// Flags indicating the valid information returned in this structure. Members that do not contain valid information are set to zero./// </summary>public int dwFlags;/// <summary>/// Current X-coordinate./// </summary>public int dwXpos;/// <summary>/// Current Y-coordinate./// </summary>public int dwYpos;/// <summary>/// Current Z-coordinate./// </summary>public int dwZpos;/// <summary>/// Current position of the rudder or fourth joystick axis./// </summary>public int dwRpos;/// <summary>/// Current fifth axis position./// </summary>public int dwUpos;/// <summary>/// Current sixth axis position./// </summary>public int dwVpos;/// <summary>/// Current state of the 32 joystick buttons. The value of this member can be set to any combination of JOY_BUTTONn flags, where n is a value in the range of 1 through 32 corresponding to the button that is pressed./// </summary>public int dwButtons;/// <summary>/// Current button number that is pressed./// </summary>public int dwButtonNumber;/// <summary>/// Current position of the point-of-view control. Values for this member are in the range 0 through 35,900. These values represent the angle, in degrees, of each view multiplied by 100./// </summary>public int dwPOV;/// <summary>/// Reserved; do not use./// </summary>public int dwReserved1;/// <summary>/// Reserved; do not use./// </summary>public int dwReserved2;};[DllImport("winmm")] public static extern int joyGetPosEx(int uJoyID, ref JOYINFOEX pji);private JOYINFOEX infoEx;private string currentButton;private string currentAxis;private float axisInput;// Use this for initializationvoid Start () {         //Device joystickDevice;         //JoystickState state;infoEx = new JOYINFOEX();infoEx.dwSize = Marshal.SizeOf(typeof(JOYINFOEX));infoEx.dwFlags=0x00000080;}// Update is called once per framevoid Update () {getButton();}/// <summary>/// get the button data of the joystick/// </summary>void getButton(){int e = joyGetPosEx(0,ref infoEx);if (e==0){int mask=0x10;string str = string.Empty;for(int i=5;i<32;i++){if ((infoEx.dwButtons & mask) > 0){str = str + string.Format("button({0})",i);}mask = mask << 1;}Debug.Log(str);}}}

这样就可以全部获取到在pc上可以显示按键。

0 1
原创粉丝点击