Unity 按键输入封装&实现第一人称移动&相机移动

实现在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 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值