前言:一直都没养成写博客的习惯,导致学了的知识老是会忘记,最近决定重心放在Unity上,于是回顾下Unity的黑魂教程,顺便强迫自己写博客。此系列参照傅老师的黑魂复刻教程学习,bilibili-av21513489
创建一个新项目,创建一个新的Plane和Capsule,position分别设置为(0,0,0)和(0,1,0) 给Capsule添加一个C#Script脚本,命名为PlayerInput
PlayerInput的功能是将玩家按键的输入转化成为竖直和水平方向上的信号量
public class PlayerInput : MonoBehaviour { public string keyUp = "w"; public string keyDown = "s"; public string keyLeft = "a"; public string keyRight = "d"; //将输入按键设置为public从而使在编辑器内可见,方便修改,写活代码 private float targetDup; private float targetDright; void Update() { targetDup = (Input.GetKey(keyUp) ? 1.0f : 0) - (Input.GetKey(keyDown) ? 1.0f : 0); targetDright = (Input.GetKey(keyRight) ? 1.0f : 0) - (Input.GetKey(keyLeft) ? 1.0f : 0); //键位输入转化成前后左右信号 } }最初版本的代码已经实现了从输入到信号的转换,但是可以发现targetDup和targetDright都是突然增长的(从0到1),这时候利用Mathf.SmoothDamp函数实现缓慢递增(衰减)。
前4个参数分别为 初值 目标值 当前速度(由函数自己计算,不需要自己求) 所用时间
//新增的代码 public float Dup; public float Dright; private float velocityDup; private float velocityDright; Dup = Mathf.SmoothDamp(Dup, targetDup, ref velocityDup, 0.1f); Dright = Mathf.SmoothDamp(Dright, targetDright, ref velocityDright, 0.1f); //线性插值获得Dup,Dright一般游戏有时候都需要暂时禁用输入模块功能,因此我们添加一个布尔型变量inputEnabled来关闭输入功能
if(inputEnabled==false) //设置控制开关 { targetDup = 0; targetDright = 0; }由此一来,最初的输入功能代码就完成了,以下为最终代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerInput : MonoBehaviour { public string keyUp = "w"; public string keyDown = "s"; public string keyLeft = "a"; public string keyRight = "d"; //将输入按键设置为public从而使在编辑器内可见,方便修改,写活代码 public float Dup; public float Dright; public bool inputEnabled = true; private float targetDup; private float targetDright; private float velocityDup; private float velocityDright; void Update() { targetDup = (Input.GetKey(keyUp) ? 1.0f : 0) - (Input.GetKey(keyDown) ? 1.0f : 0); targetDright = (Input.GetKey(keyRight) ? 1.0f : 0) - (Input.GetKey(keyLeft) ? 1.0f : 0); //键位输入转化成前后左右信号 if (inputEnabled == false) //设置控制开关 { targetDup = 0; targetDright = 0; } Dup = Mathf.SmoothDamp(Dup, targetDup, ref velocityDup, 0.1f); //线性插值获得Dup,Dright Dright = Mathf.SmoothDamp(Dright, targetDright, ref velocityDright, 0.1f); } }