unity3d 读取按键以及GetKey,GetKeyDown和GetKeyUp之间的区别
示例
输入必须从Update函数读取。
所有可用的Keycode枚举的参考。
1.阅读按键Input.GetKey:
Input.GetKey在用户按住指定键的同时将反复返回true。可以在按住指定键的同时重复发射武器。以下是按住空格键时子弹自动发射的示例。播放器不必一遍又一遍地按下并释放键。
public GameObject bulletPrefab; public float shootForce = 50f; void Update() { if (Input.GetKey(KeyCode.Space)) { Debug.Log("Shooting a bullet while SpaceBar is held down"); //实例化项目符号 GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation) as GameObject; //从子弹中获得刚体,然后向子弹添加力量 bullet.GetComponent<Rigidbody>().AddForce(bullet.transform.forward * shootForce); } }
2。用以下命令读取按键Input.GetKeyDown:
Input.GetKeyDown当按下指定的键时,将仅一次。这是Input.GetKey和之间的主要区别Input.GetKeyDown。其用法的一个示例用法是切换UI或手电筒或打开/关闭项目。
public Light flashLight; bool enableFlashLight = false; void Update() { if (Input.GetKeyDown(KeyCode.Space)) { //拨动灯 enableFlashLight = !enableFlashLight; if (enableFlashLight) { flashLight.enabled= true; Debug.Log("灯光已启用!"); } else { flashLight.enabled= false; Debug.Log("轻残疾人!"); } } }
3.用以下命令读取按键Input.GetKeyUp:
这与完全相反Input.GetKeyDown。它用于检测何时释放/释放按键。就像Input.GetKeyDown,它返回true只有一次。例如,您可以enable在按住键的同时点亮,Input.GetKeyDown然后在按下键的情况下禁用点亮Input.GetKeyUp。
public Light flashLight; void Update() { //按下空格键时禁用灯光 if (Input.GetKeyDown(KeyCode.Space)) { flashLight.enabled= true; Debug.Log("灯光已启用!"); } //释放空格键时禁用灯光 if (Input.GetKeyUp(KeyCode.Space)) { flashLight.enabled= false; Debug.Log("轻残疾人!"); } }