Unity开发之路(二):输入事件管理Input

发表于2017-12-14
评论0 3.5k浏览

在Unity输入时间有Input类来管理输入事件,常用方法:

// 键盘事件
public static bool GetKeyDwon(enum KeyCode); // 按键按下(触发一次)
public static bool GetKeyDwon(enum KeyCode); // 按键放开(触发一次)
public static bool GetKey(enum KeyCode); // 持续按下(持续触发)
// 鼠标事件 button:0-左键,1-右键,2-中间件
public static bool GetMouseButtonDown(int button); // 鼠标按下(触发一次)
public static bool GetMouseButtonUp(int button); // 鼠标放开(触发一次)
public static bool GetMouseButton(int button); // 鼠标按下(持续触发)
// 触摸时间 
public static int touchCount { get; }; // 触摸点个数  
public static Touch GetTouch(int index); // 触摸事件

TouchPhase

ValuesDescription
BeganA finger touched the screen
MovedA finger moved on the screen
StationaryA finger is touching the screen but hasn’t moved
EndedA finger was lifted from the screen. This is the final phase of a touch
CanceledThe system cancelled tracking for the touch, as when (for example) the user puts the device to her face or more than five touches happened simultaneously. This is the final phase of a touch

输入事件需要在Update方法中处理。

示例:

void Update() 
{
    if (Input.GetKey(KeyCode.D)) {
        print('button d');
    }
    if (Input.GetMouseButton(0)) {
        print('left');
    }
     while (i < Input.touchCount) {  
        if (Input.GetTouch(i).phase == TouchPhase.Began) {  
            print(i + 'began');
        }  
}
print 只能在运行时类(MonoBehaviour的子类)中使用; 
其他地方使用Debug.Log打印。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引