Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作
作者:mrr 时间:2023-06-01 18:01:45
获取当前键盘按键,代码如下:
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); 一个简单例子让小球撞破墙:
代码如下:
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
}
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅析Java中的异常处理机制
rocketmq client 日志的问题处理方式
![](https://img.aspxhome.com/file/2023/1/82461_0s.png)
详解Spring boot上配置与使用mybatis plus
Java将对象保存到文件中/从文件中读取对象的方法
简单了解JavaCAS的相关知识原理
![](https://img.aspxhome.com/file/2023/9/125259_0s.png)
C#实现json格式转换成对象并更换key的方法
openCV中meanshift算法查找目标的实现
![](https://img.aspxhome.com/file/2023/0/121670_0s.jpg)
java使用ftp上传文件示例分享
理解maven命令package、install、deploy的联系与区别
![](https://img.aspxhome.com/file/2023/4/116134_0s.png)
C#泛型详解及关键字作用
![](https://img.aspxhome.com/file/2023/6/96436_0s.png)
Struts2+uploadify多文件上传实例
![](https://img.aspxhome.com/file/2023/0/88740_0s.jpg)
C#中调用命令行cmd开启wifi热点的实例代码
![](https://img.aspxhome.com/file/2023/0/96350_0s.jpg)
jackson反序列化时如何忽略不需要的字段
Java中实现双数组Trie树实例
Spring的refresh()方法相关异常解析
SpringBoot redis分布式缓存实现过程解析
![](https://img.aspxhome.com/file/2023/1/58541_0s.png)
java 反射机制详解及实例代码
java实现合并单元格的同时并导出excel示例
Java输入/输出流体系详解
![](https://img.aspxhome.com/file/2023/9/65739_0s.png)
c语言轻松实现猜数字小游戏
![](https://img.aspxhome.com/file/2023/8/127518_0s.png)