unity 判斷滑鼠左鍵在按下的狀態

來源:互聯網
上載者:User

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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.