【Unity】7.3 鍵盤輸入

分類:Unity、C#、VS2015 編碼

建立日期:2016-04-21 spa

1、簡介

鍵盤事件也是桌面系統中的基本輸入事件。和鍵盤有關的輸入事件有按鍵按下、按鍵釋放、按鍵長按,Input類中能夠經過下圖所示的方法來處理: code

image

上面的方法經過傳入按鍵名稱字符串或者按鍵編碼KeyCode指定要判斷的按鍵。 orm

下圖所示是經常使用按鍵的按鍵名與KeyCode編碼,供讀者參考,完整的按鍵編碼請查閱Unity用戶手冊。blog

image

2、基本用法示例

下面的代碼演示瞭如何響應鍵盤按鍵事件: 事件

void Update() 字符串

{ get

//按下鍵盤A鍵 it

if(Input.GetKeyDown(KeyCode.A)) io

{

//...

}

//按住鍵盤A鍵

if(Input.GetKey(KeyCode.A))

{

//...

}

//擡起鍵盤A鍵

if(Input.GetKeyUp(KeyCode.A))

{

//...

}

//按下鍵盤左Shift鍵

if(Input.GetKeyDown(KeyCode.LeftShift))

{

//...

}

//按住鍵盤左Shift鍵

if(Input.GetKey(KeyCode.LeftShift))

{

//...

}

//擡起鍵盤左Shift鍵

if(Input.GetKeyUp(KeyCode.LeftShift))

{

//...

}

}

示例(Demo3_1_ControlExample.unity)

該例子演示如何控制模型在x平面上移動。

下面的代碼演示瞭如何獲得Horizontal軸的值

void Update () {

//獲得Horizontal軸的值

float axisH = Input.GetAxis("Horizontal");

}

下面的代碼用鍵盤方向鍵或者W、A、S、D按鍵來控制模型在x平面上移動,只須要將腳本(ControlExample.cs文件)添加到模型上便可:

using UnityEngine;
using System.Collections;
public class ControlExample : MonoBehaviour
{
    public float speed = 10.0f;          //行駛速度
    public float rotationSpeed = 100.0f; //轉向速度
    void Update()
    {
        //使用上下箭頭或者W、S鍵來控制前進後退
        float translation = Input.GetAxis("Vertical") * speed;
        //使用左右箭頭或者A、D鍵來控制左右旋轉
        float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
        translation *= Time.deltaTime;
        rotation *= Time.deltaTime;
        //在x-z平面上移動
        transform.Translate(0, 0, translation);
        transform.Rotate(0, rotation, 0);
    }
}

運行效果:

image
相關文章
相關標籤/搜索