在说标准输入的方法时,需要先了解一下Input类的功能。
鼠标输入
Input类主要的功能就是获取系统输入按键,因此获取鼠标输入的方法在Input类中。
主要的方法
- 当鼠标按下时,返回true,如果鼠标一直按下,在按下期间一直返回true
bool res = Input.GetMouseButton(参数); - 当鼠标按下时,第一帧返回true
bool res = Input.GetMouseButtonDown(参数); - 当鼠标释放后,第一帧返回true
bool res = Innput.GetMouseButtonUp(参数);
第一个方法:按下不松,每帧都会返回true;第二个方法:按下不松,只返回第一帧的true;第三个方法:按下不松,不返回,当松开以后才返回true
参数分类:0表示左键,1表示右键,2表示中键
测试:
我们创建一个脚本,将其添加给摄像机
public class cameraScript : MonoBehaviour {
public bool flag;
void Update ()
{
flag = Input.GetMouseButton(0);
}
}
我们可以看到在摄像机中有一个Flag变量,我们运行起来,可以通过该变量进行观察,在运行起来,需要鼠标点击Game面板。
当我们鼠标按下后,我们可以看到Flag已经发生变化
键盘输入
具体方法
- 通过名称指定的按键被用户按下时返回true
bool res = Input.GetKey(KeyCode.指定按键) - 当用户按下指定名称的按键时第一帧返回true
bool res = Input.GetKeyDown(Keycode.指定按键) - 当用户抬起指定名称按键的时候返回true
bool res = Input.GetKeyUp(KeyCode.指定按键)
将上面的代码改成如下:
public class cameraScript : MonoBehaviour {
public bool flag;
public bool flag2;
void Update () {
flag = Input.GetMouseButton(0);
flag2 = Input.GetKey(KeyCode.A);
}
}
如何按下组合键
我们在好多场景下,都会按下多个组合键。
我们可以通过多个判断进行实现。
实现一个镜头拉近效果
private Camera camera;
private void Start()
{
camera = GetComponent<Camera>();
}
public bool Flag = true;
private void Update()
{
if (Input.GetMouseButtonDown(1))
{
Flag = !Flag;
if (Flag)
camera.fieldOfView = 60;
else
camera.fieldOfView = 20;
}
}
方法二:使用mathf.Lerp函数
private Camera camera;
private void Start()
{
camera = GetComponent<Camera>();
}
public bool Flag = true;
private void Update()
{
if (Input.GetMouseButtonDown(1))
{
Flag = !Flag;
}
if(Flag)
{
camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, 60, 0.1f);
}
else
{
camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, 20, 0.1f);
}
}