using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Fps_Input : MonoBehaviour {
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>();
public List<string> unityAxis = new List<string>();
private void Start()
{
SetupDefaults();
}
private void SetupDefaults(string type = "")//按键初始化
{
if (type == " " || type == "buttons")
{
if (buttons.Count == 0)
{
AddButton("Fire", 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);
}
}
if (type == " " || type == "UnityAxis")//初始化unity自带轴
{
if (unityAxis.Count == 0)
{
AddUnityAxis("Mouse x");
AddUnityAxis("Mouse Y");
AddUnityAxis("Horizontal");
AddUnityAxis("Vertical");
}
}
}
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 Fps_InputAxis() { positive = pk, negative = nk };
else
axis.Add(n, new Fps_InputAxis() { positive = pk, negative = nk });
}
private void AddUnityAxis(string n)
{
if (!unityAxis.Contains(n))
unityAxis.Add(n);
}
public bool GetButton(string button)//外界调用按钮事件
{
if (buttons.ContainsKey(button))
return Input.GetKey(buttons[button]);
return false;
}
public bool GetButtonDown(string button)//外界调用按下按钮事件
{
if (buttons.ContainsKey(button))
return Input.GetKeyDown(buttons[button]);
return false;
}
public float GetAxis(string axis)//调用轴信息
{
if (this.unityAxis.Contains(axis))
return Input.GetAxis(axis);
else
return 0;
}
public float GetAxisRaw(string axis)//调用固定值轴信息
{
if (this.axis.ContainsKey(axis))
{
float val = 0;
if (Input.GetKey(this.axis[axis].positive))
return 1;
if (Input.GetKey(this.axis[axis].negative))
return -1;
return val;
}
else if (unityAxis.Contains(axis))
{
return Input.GetAxisRaw(axis);
}
return 0;
}
}
第一人称射击游戏(2)-按键输入封装
最新推荐文章于 2020-06-30 22:34:25 发布