键盘和鼠标
本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 45 课,共 60 课。
Input System 会为每个设备提供一个对象。Keyboard.current 是键盘,键盘上的每个按键都是一个带有名称的控件:spaceKey、aKey、upArrowKey,或者通过按键的 Key 值获取任意按键的 Keyboard.current[Key.Space]。Mouse.current 是鼠标,包含 leftButton、rightButton 和 position。按住控件时,每一帧它的 isPressed 都是 true,和 Input.GetKey 一样。这个潜艇用方向键下潜和上浮,并在按住鼠标按钮时打开探照灯:
using UnityEngine;
using UnityEngine.InputSystem;
public class Submarine : MonoBehaviour
{
public float diveSpeed = 2f;
public Light searchlight;
void Update()
{
Keyboard keyboard = Keyboard.current;
if (keyboard == null) return; // 没有连接键盘
if (keyboard.downArrowKey.isPressed)
transform.position += Vector3.down * diveSpeed * Time.deltaTime;
if (keyboard.upArrowKey.isPressed)
transform.position += Vector3.up * diveSpeed * Time.deltaTime;
searchlight.enabled = Mouse.current != null && Mouse.current.leftButton.isPressed;
}
}current 是最近使用的设备,没有设备时它的值为 null:手机或游戏主机可能没有键盘,空值检查可以避免脚本在这些设备上抛出错误。键盘没有轴,因此向下箭头和 S 是两个独立的按键:如果潜艇也应该在按下 S 时下潜,可以检查 keyboard.downArrowKey.isPressed || keyboard.sKey.isPressed。Mouse.current.position.ReadValue() 会返回一个 Vector2,表示指针在屏幕像素坐标中的位置,坐标原点位于左下角,和 Input.mousePosition 一样。
挑战
中等使用 Keyboard.current 和 Mouse.current 驾驶热气球。
- 按住
rightArrowKey或dKey时,气球以每秒drift个单位沿 +x 方向移动;按住leftArrowKey或aKey时,沿 -x 方向移动。 - 按下
spaceKey或leftButton时,bool burner为真;调用flame.SetActive(burner);。 - 燃烧器开启时,以
rise的速度上升;关闭时,以sink的速度下降,但不会低于groundY。
按“开始”并驾驶热气球:按住空格键或鼠标按钮即可上升。然后按“检查”。
亲手试试
using UnityEngine;
using UnityEngine.InputSystem;
public class Balloon : MonoBehaviour
{
public float drift = 2f;
public float rise = 3f;
public float sink = 1f;
public float groundY = 2f;
public GameObject flame;
void Update()
{
// 用方向键或 A 和 D 键控制漂移,用空格键或鼠标点燃火焰
}
}
打造真正的游戏中的所有课
自己练习: Unity 在线编辑器