unity 中擷取輸入的類是Input。如判斷是否有Delete鍵按下
if (Input.GetKeydown( KeyCode.Delete ))
{
// do something
}
查看Input這個類的提供的方法,有個GetMouseButtonDown(), 參數為0表示左鍵,那麼如果我們想知道左鍵是不是按下的狀態那是不是就可以直接:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log( "mouse left button is down" );
}
}
似乎沒有任何問題。但是如果你把代碼加入到你的測試程式中,運行程式,就會發現,當你按下滑鼠並且不鬆開的時候雖然能輸出“mouse left button is down”,但是只是幾個而已,而不是我們期望的,如果不鬆開,會一直列印 mouse left button is down。這時候鬆開,在按下有只輸出幾個而已。
為什嗎?我們再看看它的協助:
You need to call this function from the
Update function, since the state gets reset each frame.It will not return true until the user has released the mouse button and pressed it again.button values are 0 for left button, 1 for right button, 2 for the middle button.
原來這個狀態-按下的狀態 只會持續幾幀的狀態,協助中說每一幀都會重設,測試的結果並不是這樣,能夠持續幾幀,之後就會重設。也就是幾幀之後就這個函數返回false了。
跟這個函數類似的還有一個:GetButtonDown(), 文檔說明如下:
You need to call this function from the
Update function, since the state gets reset each frame.It will not return true until the user has released the key and pressed it again.
那我們到底得用什麼方法,後來試過很多方法,發現 GetButton()這個可以達到想要的效果,只要滑鼠是按下狀態,這個函數就一直返回true,不過注意滑鼠左鍵這個時候變成了"fire1".
var projectile :
GameObject;
function Update () {
if (Input.GetButtonDown ("Fire1")) {
Instantiate (projectile, transform.position, transform.rotation);
}
}
上面這是個使用的例子。
如果你是想判斷滑鼠在一個情境中的物體上按下和抬起,就可以直接重載
void OnMouseDown()
void OnMouseUp()