Menu
CoddyTech

本帧按下

本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 46 课,共 60 课。

isPressed 会在按住期间的每一帧回答“现在按下了吗?”。对于只应在每次按下时触发一次的操作,控件还有另外两个状态:wasPressedThisFrame 只有在按键或按钮按下的那一帧才是 true,wasReleasedThisFrame 只有在按键或按钮松开的那一帧才是 true。它们可以替代 Input.GetKeyDown 和 Input.GetKeyUp,以及 GetMouseButtonDown 和 GetMouseButtonUp。这个橡皮图章会在鼠标按钮按下时落下,松开时抬起:

using UnityEngine;
using UnityEngine.InputSystem;

public class Stamp : MonoBehaviour
{
    public float drop = 0.5f;
    private int stamps;

    void Update()
    {
        Mouse mouse = Mouse.current;

        if (mouse.leftButton.wasPressedThisFrame)
        {
            transform.position += Vector3.down * drop;
            stamps++;
            Debug.Log("Stamp " + stamps);
        }
        if (mouse.leftButton.wasReleasedThisFrame)
        {
            transform.position += Vector3.up * drop;
        }
    }
}

按住鼠标点击半秒,只会记录一次 Stamp 1,图章也只会落下一次再抬起一次。如果第一个 if 中使用 isPressed,同一次点击大约会记录 30 次图章,并让图章沉入桌面 15 个单位。按键的工作方式也一样:每次按下空格键时,Keyboard.current.spaceKey.wasPressedThisFrame 都只会有一帧为 true。

challenge icon

挑战

中等

按下空格键让短跑运动员做好起跑准备:向下蹲,然后向上起跑。

  1. 在 Update() 中,当 !running 且 Keyboard.current.spaceKey.wasPressedThisFrame 时:设置 set,向下移动 crouch,记录 Set。
  2. 当 set 且 wasReleasedThisFrame 时:清除 set,设置 running,向上移动 crouch,记录 Go!。
  3. 当 running 时,以每秒 speed 个单位的速度沿 +z 方向移动。

点击“开始”,按住空格键再松开:控制台中会先显示 Set,再显示 Go!。然后点击“检查”。

亲手试试

using UnityEngine;
using UnityEngine.InputSystem;

public class Sprinter : MonoBehaviour
{
    public float speed = 6f;
    public float crouch = 0.3f;

    private bool set;
    private bool running;

    void Update()
    {
        // 按下 Space:蹲下并记录 Set。松开 Space:站起来,记录 Go! 并开始奔跑。
    }
}

打造真正的游戏中的所有课

自己练习: Unity 在线编辑器