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當對應的虛擬按鈕被按住時。
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 } } }
相關文章
詳解c#中Array,ArrayList與List<T>的區(qū)別、共性與相互轉(zhuǎn)換
本文詳細講解了c#中Array,ArrayList與List<T>的區(qū)別、共性與相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12詳解C#中多態(tài)性學習/虛方法/抽象方法和接口的用法
這篇文章主要為大家詳細介紹了C#中多態(tài)性學習、虛方法、抽象方法和接口的用法的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-03-03C#/VB.NET實現(xiàn)將XML轉(zhuǎn)為PDF
可擴展標記語言(XML)文件是一種標準的文本文件,它使用特定的標記來描述文檔的結(jié)構以及其他特性。本文將利用C#實現(xiàn)XML文件轉(zhuǎn)PDF?,需要的可以參考一下2022-03-03