任何一款游戏都必须和用户进行交互才行,最常用的就是通过键盘和鼠标进行交互,在 Unity
中想要获取用户的键盘或鼠标的事件的话,就必须使用 Input
类来获取。
打开 Unity ,新建一个空的项目,创建一个 Cube 物体:

然后给这个 Cube 物体添加一个新脚本:


创建完成后,双击打开此脚本,就需要写一些代码了,如果想要获取用户按键或鼠标点击的事件,那就需要使用 Input
类。一般来说 Input
类的方法需要写在 Update()
方法中。
using UnityEngine;
using System.Collections;
public class CubeScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
// 获取用户的键盘和鼠标点击事件需要用到 Input 类
void Update () {
// 每帧都需要监听用户的事件
// 在当前这一帧中,如果用户按下了 W 就会返回 true,否则返回 false
bool keyCodeDown = Input.GetKeyDown (KeyCode.W);
// 检测键盘按下
if (keyCodeDown) {
// print 只能在 MonoBehaviour 的子类中使用,其他情况只能使用 Debug.Log() 输出
print ("往前走");
}
if (Input.GetKeyDown (KeyCode.S)) {
Debug.Log("往后退");
}
// 检测键盘弹起
if (Input.GetKeyUp (KeyCode.Alpha1)) {
Debug.Log("按下 1 键,弹起");
}
//按下鼠标左键
if (Input.GetMouseButtonDown (0)) {
print ("按下鼠标左键");
}
//按下鼠标右键
if (Input.GetMouseButtonDown (1)) {
print ("按下鼠标右键");
}
//按下鼠标中键
if (Input.GetMouseButtonDown (2)) {
print ("按下鼠标中键");
}
}
}
点击运行按钮, 按下 W 之后,如下图输出

则说明已经成功的接收到了用户按下键盘的事件。
网友评论