Unity3D獲取當前鍵盤按鍵及Unity3D鼠標、鍵盤的基本操作
獲取當前鍵盤按鍵,代碼如下:
using UnityEngine;
using System.Collections;
public class GetCurrentKey : MonoBehaviour {
KeyCode currentKey;
void Start ()
{
currentKey = KeyCode.Space;
}
void OnGUI()
{
if (Input.anyKeyDown)
{
Event e = Event.current;
if (e.isKey)
{
currentKey = e.keyCode;
Debug.Log("Current Key is : " + currentKey.ToString());
}
}
}
}
下面給大家介紹Unity3D鼠標、鍵盤的基本操作
鍵盤:
GetKey 當通過名稱指定的按鍵被用戶按住時返回true
GetKeyDown 當用戶按下指定名稱的按鍵時的那一幀返回true。
GetKeyUp 在用戶釋放給定名字的按鍵的那一幀返回true。
GetAxis(“Horizontal")和GetAxis(“Verical”) 用方向鍵或WASD鍵來模擬-1到1的平滑輸入
鍵盤判斷:
If(Input.GetKeyDown(KeyCode.A)){//KeyCode表示包含鍵盤所有鍵
print(“按下A鍵”); } If(Input.GetKeyUp(KeyCode.D)){//當按D鍵松開時
print(“松開D鍵”); } If(Input.GetAxis(“Horizontal")){//當按下水平鍵時
print(“按下水平鍵”); } If(Input.GetKeyUp("Verical“)){當按下垂直鍵時
print(“按下垂直鍵”); }
鼠標:
GetButton 根據(jù)按鈕名稱返回true當對應(yīng)的虛擬按鈕被按住時。
GetButtonDown 在給定名稱的虛擬按鈕被按下的那一幀返回true。
GetButtonUp 在用戶釋放指定名稱的虛擬按鈕時返回true。
鼠標判斷:
if(Input.GetButton("Fire1")){//Fire1表示按下鼠標左鍵
print(“按下鼠標左鍵”); } if (Input.GetMouseButton(0)) {//0表示鼠標左鍵
Debug.Log("按下鼠標左鍵"); } if (Input.GetMouseButton(1)) {//1表示鼠標右鍵
Debug.Log("按下鼠標右鍵"); } if (Input.GetMouseButton(2)) {//2表示鼠標中鍵
Debug.Log("按下鼠標中鍵"); }
給物體施加普通力:
1、先給物體添加剛體
2、transform.rigidbody.AddForce(0,0,1000); 一個簡單例子讓小球撞破墻:

代碼如下:
using UnityEngine;
using System.Collections;
public class Cube : MonoBehaviour { // Use this for initialization
void Start () { } // Update is called once per frame void Update () {
if(Input.GetKey(KeyCode.W)){//當鼠標按下W鍵時,小球向前移動
transform.Translate(Vector3.forward);
}
if(Input.GetKey(KeyCode.S)){當鼠標按下S鍵時,小球向后移動
transform.Translate(Vector3.back);
天貓雙十一活動
} if(Input.GetKey(KeyCode.A)){當鼠標按下A鍵時,小球向左移動
transform.Translate(Vector3.left);
}
if(Input.GetKey(KeyCode.D)){當鼠標按下D鍵時,小球向右移動
transform.Translate(Vector3.right);
} if(Input.GetButton("Fire1")){//當點擊鼠標左鍵時,小球撞塌墻
transform.rigidbody.AddForce(0,0,200);//物體向前移動的力為200
}
}
}
相關(guān)文章
C#實現(xiàn)基于IE內(nèi)核的簡單瀏覽器完整實例
這篇文章主要介紹了C#實現(xiàn)基于IE內(nèi)核的簡單瀏覽器,較為詳細的分析了C#實現(xiàn)瀏覽器的原理與主要功能實現(xiàn)方法,并附帶完整實例供大家下載,需要的朋友可以參考下2015-07-07
關(guān)于C#10 新特性 Lambda 優(yōu)化
這篇文章主要介紹了C# 10 新特性 Lambda 優(yōu)化,C# 10 對于 Lambda 做了很多的優(yōu)化,我們可以在 C# 中更加方便地使用委托和 Lambda 了,下面就來看一些示例,需要的朋友也可以參考一下2021-11-11
C#12中的Primary?Constructors主構(gòu)造函數(shù)詳解
主構(gòu)造函數(shù)把參數(shù)添加到class與record的類聲明中就是主構(gòu)造函數(shù),這篇文章主要介紹了C#12中的Primary?Constructors 主構(gòu)造函數(shù),需要的朋友可以參考下2023-11-11
基于Kubernetes實現(xiàn)前后端應(yīng)用的金絲雀發(fā)布(兩種方案)
這篇文章主要介紹了基于Kubernetes實現(xiàn)前后端應(yīng)用的金絲雀發(fā)布,文中給大家提到了兩種常用方案,通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2021-12-12

