7.1 键盘事件
在游戏开发中要监听键盘按下的事件、键盘抬起的事件,键盘长按事件和键盘连按事件等。
7.1.1键盘按下事件。
在脚本中,通过Input。GetKeyDown()方法中将按键值作为参数传入即可判断按键是否被按下,如果按键被按下,该方法将返回true,没有按下则返回false。
using UnityEngine;
using System.Collections;
public class key : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.W))
{
Debug.Log("您按下了W键");
}
if(Input.GetKeyDown(KeyCode.A))
{
Debug.Log("您按下了A键");
}
if(Input.GetKeyDown(KeyCode.S))
{
Debug.Log("您按下了S键");
}
if(Input.GetKeyDown(KeyCode.D))
{
Debug.Log("您按下了D键");
}
if(Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("您按下了空格键");
}
}
}
7.1.2键盘抬起事件
抬起事件的产生完全依赖于按下事件,因为只有键盘执行按下事件后,系统才会调用键盘抬起事件。
在代码中,使用Input.GetKeyUp()方法得到某按键的抬起事件,该方法的参数为按键的键值。键盘抬起后,该方法返回true,否则返回false。
using UnityEngine;
using System.Collections;
public class key : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.W))
{
Debug.Log("您按下了W键");
}
if(Input.GetKeyDown(KeyCode.A))
{
Debug.Log("您按下了A键");
}
if(Input.GetKeyDown(KeyCode.S))
{
Debug.Log("您按下了S键");
}
if(Input.GetKeyDown(KeyCode.D))
{
Debug.Log("您按下了D键");
}
if(Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("您按下了空格键");
}
//抬起按键
if(Input.GetKeyUp(KeyCode.W))
{
Debug.Log("您抬起了W键");
}
if(Input.GetKeyUp(KeyCode.A))
{
Debug.Log("您抬起了A键");
}
if(Input.GetKeyUp(KeyCode.S))
{
Debug.Log("您抬起了S键");
}
if(Input.GetKeyUp(KeyCode.D))
{
Debug.Log("您抬起了D键");
}
if(Input.GetKeyUp(KeyCode.Space))
{
Debug.Log("您抬起了空格键");
}
}
}
7.1.3 键盘长按事件
键盘长按事件可监听键盘中某个按键是否一直处于按下状态,比如飞行射击游戏中,玩家长按开火键,子弹会一直处于发射状态。
在代码中,可以使用Input。GetKey()方法判断键盘中某个按键是否一直处于按下状态。
为了更清晰地观察键盘长按事件,本例在程序中声明了一个整型变量keyFrame来记录键盘长按下的时间,使用Input.GetKey()方法记录按下的时间帧数,然后直接将时间帧数打印出来。
using UnityEngine;
using System.Collections;
public class longkey : MonoBehaviour {
//记录某按键按下的帧数
int keyFrame=0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A按下一次");
}
if(Input.GetKey(KeyCode.A))
{
//记录按下的帧数
keyFrame++;
Debug.Log("A连按"+keyFrame+"帧");
}
if(Input.GetKeyUp(KeyCode.A))
{
//抬起后清空帧数
keyFrame=0;
Debug.Log("A按键抬起");
}
}
}
7.1.4任意键事件
在程序中,还可以监听键盘中任意按键是否被按下。在常见的游戏中,读取完资源后,会提示玩家按任意键继续操作,它的实现原理就是在操作界面中用程序监听终端任意键是否按下。
下述代码,监听任意键是否被按下,并且将按下的时间帧数打印在屏幕当中。
在脚本中,当Input.anyKeyDown引用的取值为true时,表示有任意按键被按下当Input.anyKey引用的取值为true时,表示有任意按键处于长按当中。
using UnityEngine;
using System.Collections;
public class anykey : MonoBehaviour {
//记录某按键按下的帧数
int keyFrame=0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.anyKeyDown)
{
//清空按下帧数
keyFrame=0;
Debug.Log("任意键被按下");
}
if(Input.anyKey)
{
keyFrame++;
Debug.Log("任意键被长按"+keyFrame+"帧");
}
}
}