实现在Unity中重新封装按键输入
1.创建脚本Input.cs
//自定义轴
public class fps_InputAxis
{
public KeyCode positive;
public KeyCode negative;
}
//自定义按键集合
public Dictionary<string, KeyCode> buttons = new Dictionary<string, KeyCode>();
//自定义轴集合
public Dictionary<string, fps_InputAxis> axis = new Dictionary<string, fps_InputAxis>();
//Unity轴集合
public List<string> unityAxis = new List<string>();
1.1 初始化方法
void Start(){
SetupDefaults();
}
private void SetupDefaults(string type = ""){
//初始化按键
if (type == "" || type == "button"){
if (buttons.Count == 0){
AddButton("File", KeyCode.Mouse0); //开火
AddButton("Reload", KeyCode.R); //装弹
AddButton("Jump", KeyCode.Space); //跳跃
AddButton("Crouch", KeyCode.C); //蹲伏
AddButton("Sprint", KeyCode.LeftShift); //冲刺
}
}
//初始化自定义轴
if (type == "" || type == "Axis"){
if (axis.Count == 0){
AddAxis("Horizontal", KeyCode.W, KeyCode.S);
AddAxis("Vertical", KeyCode.A, KeyCode.D);
}
}
//初始化unity轴
if (type == "" || type == "UnityAxis"){
if (unityAxis.Count == 0){
AddUnityAxis("Mouse X");
AddUnityAxis("Mouse Y");
AddUnityAxis("Horizontal");
AddUnityAxis("Vertical");
}
}
}
1.2 添加按键、轴方法
//添加按键
private void AddButton(string n, KeyCode k){
if (buttons.ContainsKey(n))
buttons[n] = k;
else
buttons.Add(n, k);
}
//添加自定会轴
private void AddAxis(string n, KeyCode pk, KeyCode nk){
if (axis.ContainsKey(n))
axis[n] = new