【Unity】7.2 鼠標輸入

分類:Unity、C#、VS2015 spa

建立日期:2016-04-21 code

1、簡介

在桌面系統的遊戲中,鼠標輸入是最基本的輸入方式之一。遊戲不少操做都須要鼠標來完成,例如武器的瞄準和開火、菜單的單擊、物體的拾取等。 orm

鼠標輸入的相關事件包括鼠標移動、按鍵的單擊等。 blog

Input類中和鼠標輸入有關的方法和變量以下圖所示: 遊戲

image

在Unity中,鼠標位置用屏幕的像素座標表示,屏幕左下角爲座標原點(0,0),右上角爲(screen.width,screen.height),其中screen.width爲屏幕分辨率的寬度,screen.height爲屏幕分辨率的高度。 事件

mousePosition的變量類型爲Vector3,,其中x份量對應水平座標,y份量對應垂直座標,z份量始終爲0。 get

CetMouseButtonDown、CetMouseButtonUp、CetMouseButton這3個方法須要傳入參數來指定判斷哪一個鼠標按鍵,0對應左鍵,1對應右鍵,2對應中鍵。 it

2、基本用法示例

下面的代碼演示瞭如何響應鼠標單擊事件(0對應鼠標左鍵,1對應鼠標右鍵,2對應鼠標中鍵)。 io

void Update() form

{

//按下鼠標左鍵

if(Input.GetMouseButtonDown(0))

{

//...

}

//按住鼠標左鍵

if(Input.GetMouseButton(0))

{

//...

}

//擡起鼠標左鍵

if(Input.GetMouseButtonUp(0))

{

//...

}

//按下鼠標右鍵

if(Input.GetMouseButtonDown(1))

{

//...

}

//按住鼠標右鍵

if(Input.GetMouseButton(1))

{

//...

}

//擡起鼠標右鍵

if(Input.GetMouseButtonUp(1))

{

//...

}

}

示例(Demo2_1_RotateExample.unity)

該例子演示如何根據鼠標移動距離來旋轉模型進行觀察。

將下面的腳本(RotateExample.cs文件)添加到要旋轉的模型上,模型就會跟隨鼠標的移動而旋轉:

using UnityEngine;
using System.Collections;

public class RotateExample : MonoBehaviour
{
    public float horizontalSpeed = 6.0f;
    public float verticalSpeed = 6.0f;
    void Update()
    {
        float h = horizontalSpeed * Input.GetAxis("Mouse X");
        float v = verticalSpeed * Input.GetAxis("Mouse Y");
        transform.Rotate(v, h, 0);
    }
}

運行效果:

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