功能描述
Unity自带有个Input类,它能对键盘,手柄等一些常用的输入设备进行输入检测
但是对于街机和一些其他设备的按键检测就不适用了。
所以我们来做一个仿Input类来实现一些简单的按钮检测功能
此代码本质上就是对接dll
原理:通过协程每一帧对按键状态进行检测
代码
InputCtrl: 输入检测,记录
- KeyCode:设备上面的按钮,自定义枚举
- KeyStage: 按钮实时状态
- KeyDownStage: 按钮按下瞬间状态(按下瞬间值会变成true下一帧变回false)
- KeyUpStage:按钮抬起瞬间状态
检测方法:
- GetKey() ,
- GetKeyDown(),
- GetKeyUp(),
硬件调用:
- KeyDown();
- KeyUp();
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// 输入检测代码
/// </summary>
public class InputCtrl : SingleOnMono<InputCtrl>
{
public enum KeyCode
{
KEY_NONE = 0,
KEY_BTN1,
KEY_BTN2,
}
private Dictionary<KeyCode, bool> KeyStage = new Dictionary<KeyCode, bool>();
private Dictionary<KeyCode, bool> KeyDownStage = new Dictionary<KeyCode, bool>();
private Dictionary<KeyCode, bool> KeyUpStage = new Dictionary<KeyCode, bool>();
private void Awake()
{
//这里的循环到枚举的最后一位即可
for (int i = 0; i < (int)KeyCode.KEY_BTN2; i++)
{
KeyStage.Add((KeyCode)i, false);
KeyDownStage.Add((KeyCode)i, false);
KeyUpStage.Add((KeyCode)i, false);
}
}
//获取按钮状态
public bool GetKey(KeyCode key)
{
return KeyStage[key];
}
//按钮按下检测
public bool GetKeyDown(KeyCode key)
{
return KeyDownStage[key];
}
//按钮抬起检测
public bool GetKeyUp(KeyCode key)
{
return KeyUpStage[key];
}
//按钮按下
public void KeyDown(KeyCode key)
{
KeyStage[key] = true;
StartCoroutine(IeKeyDown(key));
}
//按钮抬起
public void KeyUp(KeyCode key)
{
KeyStage[key] = false;
StartCoroutine(IeKeyUp(key));
}
IEnumerator IeKeyDown(KeyCode key)
{
KeyDownStage[key] = true;
yield return null;
KeyDownStage[key] = false;
}
IEnumerator IeKeyUp(KeyCode key)
{
KeyUpStage[key] = true;
yield return null;
KeyUpStage[key] = false;
}
}
SingleOnMono:随便写的一个继承MonoBehaviour的单例父类
using UnityEngine;
public class SingleOnMono<T> : MonoBehaviour where T : MonoBehaviour
{
public static T _instace;
public static T GetInstace()
{
if (_instace == null)
{
GameObject gbj = new GameObject();
gbj.name = typeof(T).ToString();
_instace = gbj.AddComponent<T>();
DontDestroyOnLoad(gbj);
}
return _instace;
}
}
使用示范
private void Update()
{
//自定义的
if (InputCtrl.GetInstace().GetKeyDown(InputCtrl.KeyCode.KEY_BTN1))
{
Debug.Log("设备按钮 1 按下");
}
//Unity原来的 Input
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A键按下");
}
}
其他
当然如果硬件那边给你留了接口那就不需要再写这么个方法了。