Input类允许我们通过键盘,鼠标,触摸屏等方式从用户那里接收输入
按键状态
Input.anyKey 按下任意键都会返回true
Input.anyKeyDown 只有在按下任意按键的那一帧会返回true
Input.GetKey(KeyCode key) 按下指定按键返回true
Input.GetKeyDown(KeyCode key) 在按下指定按键的那一帧返回true
Inpur.GetKeyUp(KeyCode key) 在指定按键被按下后抬起的那一帧返回true
if(Input.anyKey)
{
Debug.Log("anyKey");
}
if(Input.anyKeyDown)
{
Debug.Log("anyKeyDown");
}
if(Input.GetKey(KeyCode.Q))
{
Debug.Log("Q");
}
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("Q Down");
}
if (Input.GetKeyUp(KeyCode.Q))
{
Debug.Log("Q Up");
}
按钮状态
Input.GetButton(string buttonName) 按下指定虚拟按钮就会返回true
Input.GetBunttonDown(string buttonName) 按下指定虚拟按钮的那一帧返回true
Input.GetBunttonUp(string buttonName) 松开指定虚拟按钮的那一帧返回true
if(Input.GetButton("Jump"))
{;
Debug.Log("Jump");
}
if (Input.GetButtonDown("Jump"))
{ ;
Debug.Log("Jump Down");
}
if (Input.GetButtonUp("Jump"))
{
;
Debug.Log("Jump Up");
}
鼠标状态、位置和移动
Input.mousePosition 返回鼠标当前的位置
Input.mousePresent 判断当前是否连接鼠标
Input.mouseScrollDelta 获取鼠标滚轮的移动量
Input.GetMouseButton(int btType) 点击或按着鼠标返回true
Input.GetMouseButtonDown(int btType) 点击鼠标返回true
Input.GetMouseButtonUp(int byType) 松开鼠标返回true
if(Input.mousePresent) //如果有接入鼠标
{
if (Input.GetMouseButton(0))
{
Debug.Log("鼠标左键持续按下");
}
if (Input.GetMouseButtonDown(0))
{
Debug.Log("鼠标左键按下");
}
if (Input.GetMouseButtonUp(0))
{
Debug.Log("鼠标左键抬起");
}
if (Input.GetMouseButton(1))
{
Debug.Log("鼠标右键持续按下");
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("鼠标右键按下");
}
if (Input.GetMouseButtonUp(1))
{
Debug.Log("鼠标右键抬起");
}
if (Input.GetMouseButton(2))
{
Debug.Log("鼠标中键持续按下");
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("鼠标中键按下");
}
if (Input.GetMouseButtonUp(2))
{
Debug.Log("鼠标中键抬起");
}
Debug.Log("鼠标位置:" + Input.mousePosition);
Debug.Log("鼠标滚轮:" + Input.mouseScrollDelta);
}
Input.GetAxis(string axisName)与Input.GetAxisRaw(string axisName)
Input.GetAxis(string axisName) //获取指定轴的值 会进行插值范围在-1~1变动
此值的含义取决于输入控制的类型,例如,对于游戏杆的水平轴,值为 1 表示游戏杆向右推到底,值为 -1 表示游戏杆向左推到底;值为 0 表示游戏杆处于中性位置。
如果将轴映射到鼠标,该值会有所不同,并且不会在 -1...1 的范围内。此时,该值为当前鼠标增量乘以轴灵敏度。通常,正值表示鼠标向右/向下移动,负值表示鼠标向左/向上移动。
次值与帧率无关;使用该值时,您无需担心帧率变化问题。Input.GetAxisRaw(string axisName) //获取指定轴的值 但是是瞬间变动的 值在-1 0 1中取值
关于axisName
如果设置输入或查看axisName的选项 可以在Edit->ProjectSetting->input 可以调出InputManager,然后展开Axes可以查看当前输入的列表,可以选择其中一个转为axisName。
要重命名输入或更改 Positive Button 等,可以展开其中一个选项,然后在 Name 字段或 Positive Button 字段中更改名称。此外,请将 Type 更改为 Joystick Axis。要添加新的输入,请将 Size 字段中的数字加 1。
//可以对比一些x和x2 y和y2的取值
float x = Input.GetAxis("Horizontal"); //获取X轴
float y = Input.GetAxis("Vertical"); //获取Y轴 vertical在3D中应该对应物体的z轴
Debug.Log("x="+x);
Debug.Log("y="+y);
float x2 = Input.GetAxisRaw("Horizontal"); //获取X轴
float y2 = Input.GetAxisRaw("Vertical"); //获取Y轴 vertical在3D中应该对应物体的z轴
Debug.Log("x2="+x2);
Debug.Log("y2="+y2);