什么时候在我的代码中实现 WASD 键?

When are WASD keys implemented in my code?

我正在为播放器编写 C# 脚本,它使用 WASD 键来回移动。我的脚本如下。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAction : MonoBehaviour
{
    public Rigidbody rigid;
    public float horizontal;
    public float vertical;
    public float rate = 30.5f;
    // Start is called before the first frame update
    void Start()
    {
        rigid = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        Vector3 direction = new Vector3(horizontal, 0.0f, vertical);
        rigid.AddForce(direction * rate);
    }
}

我的代码完全没有问题,但是,我只是想知道 WASD 键是如何已经实现的。有人可以解释一下吗?

Unity 的输入由 Input Manager 控制(编辑 --> 项目设置,然后 select 输入类别)。

输入管理器使用以下类型的控件:

  1. Key 是指物理键盘上的任意键,例如 W、Shift 或 space 栏。 按钮是指物理控制器(例如游戏手柄)上的任何按钮,例如 Xbox One 上的 X 按钮 控制器
Input.GetKey("Jump") {...};
  1. 一个虚轴(复数:axes)映射到一个控件,比如a 按钮或钥匙。当用户激活控件时,轴接收一个值 [-1..1] 的范围。您可以在脚本中使用此值
horizontal = Input.GetAxis("Horizontal");

您的代码行引用了输入管理器中定义的名为“Horizo​​ntal”的 Axis。该轴本身实现了肯定按钮和否定按钮。在本例中 A/D,然后您可以在代码中间接获取输入。