首页 > 编程 > C# > 正文

Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作

2019-10-29 21:36:38
字体:
来源:转载
供稿:网友

这篇文章主要介绍了Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作的相关资料,需要的朋友可以参考下

获取当前键盘按键,代码如下:

 

 
  1. using UnityEngine; 
  2. using System.Collections; 
  3. public class GetCurrentKey : MonoBehaviour { 
  4. KeyCode currentKey; 
  5. void Start () 
  6. currentKey = KeyCode.Space; 
  7. void OnGUI() 
  8. if (Input.anyKeyDown) 
  9. Event e = Event.current; 
  10. if (e.isKey) 
  11. currentKey = e.keyCode; 
  12. 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 根据按钮名称返回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); 一个简单例子让小球撞破墙:

Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作

代码如下:

 

 
  1. using UnityEngine;  
  2. using System.Collections;  
  3. public class Cube : MonoBehaviour { // Use this for initialization  
  4. void Start () { } // Update is called once per frame void Update () {  
  5. if(Input.GetKey(KeyCode.W)){//当鼠标按下W键时,小球向前移动  
  6. transform.Translate(Vector3.forward);  
  7. }  
  8. if(Input.GetKey(KeyCode.S)){当鼠标按下S键时,小球向后移动  
  9. transform.Translate(Vector3.back);  
  10. 天猫双十一活动 
  11. if(Input.GetKey(KeyCode.A)){当鼠标按下A键时,小球向左移动  
  12. transform.Translate(Vector3.left);  
  13. }  
  14. if(Input.GetKey(KeyCode.D)){当鼠标按下D键时,小球向右移动  
  15. transform.Translate(Vector3.right);  
  16. if(Input.GetButton("Fire1")){//当点击鼠标左键时,小球撞塌墙  
  17. transform.rigidbody.AddForce(0,0,200);//物体向前移动的力为200  
  18. }  
  19. }  


注:相关教程知识阅读请移步到c#教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表