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

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

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class JoystickController : MonoBehaviour {


public struct JOYINFOEX
{
/// 
/// Size, in bytes, of this structure.
/// 
public int dwSize;
/// 
/// Flags indicating the valid information returned in this structure. Members that do not contain valid information are set to zero.
/// 
public int dwFlags;
/// 
/// Current X-coordinate.
/// 
public int dwXpos;
/// 
/// Current Y-coordinate.
/// 
public int dwYpos;
/// 
/// Current Z-coordinate.
/// 
public int dwZpos;
/// 
/// Current position of the rudder or fourth joystick axis.
/// 
public int dwRpos;
/// 
/// Current fifth axis position.
/// 
public int dwUpos;
/// 
/// Current sixth axis position.
/// 
public int dwVpos;
/// 
/// 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.
/// 
public int dwButtons;
/// 
/// Current button number that is pressed.
/// 
public int dwButtonNumber;
/// 
/// 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.
/// 
public int dwPOV;
/// 
/// Reserved; do not use.
/// 
public int dwReserved1;
/// 
/// Reserved; do not use.
/// 
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 initialization
	void Start () {
         //Device joystickDevice;
         //JoystickState state;
		infoEx = new JOYINFOEX();
		infoEx.dwSize = Marshal.SizeOf(typeof(JOYINFOEX));
		infoEx.dwFlags=0x00000080;
	}
	
	// Update is called once per frame
	void Update () 
	{
		getButton();
		
	
	}
	/// 
	/// get the button data of the joystick
	/// 
	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上可以显示按键。

你可能感兴趣的:(unity基础开发----unity获取外部设备(方向盘)按键)