Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作
Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作
发布时间:2016-12-28 来源:查字典编辑
摘要:获取当前键盘按键,代码如下:usingUnityEngine;usingSystem.Collections;publicclassGetC...

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

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 根据按钮名称返回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; 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#教程学习
热门C#教程学习
编程开发子分类