前言
教程只提供实际操作,不对知识点进行讲解。 详细知识点为下方链接 docs.unity3d.com/Packages/co…
InputSystem的安装
面板路径:Window->Package Manager
面板左上角下拉框选择Unity Rigistry(unity仓库)
右上角搜索InputSystem,点击安装。安装后会重启。
InputAction的创建
project面板中右键新建InputAction(列表最后一项)。
InputAction面板从左到右三个部分分别为Action Maps、Actions、Action Properties。\
按照上图方式创建Action,注意Action的Properties为Value,类型为Vec2
PlayerInput的使用
首先节点关系为Player/RoleMesh(模型)
我们锁定Player节点,在Inspector窗口中点击Add Component添加PlayerInput(搜索框中搜索)
最后Actions.DefaultMap选择InputAction中创建的Player Action Map
Behavior选择Send Messages。该选项会给所在的对象的逻辑脚本发送消息,自动调用函数。符合事件驱动。
在逻辑脚本中函数名严格符合On+Action名称。
逻辑脚本
下方代码的OnMovement和OnLook分别对应处理Movement和Look两个Action。
而后在Update中更新节点位置和方向。
如果是通过刚体运动,则在FixUpdate中使用相关代码更新位置。
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float rotationSpeed = 100f;
private Vector2 currentMoveInput;
private Vector2 currentLookInput;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 moveDirecrtion = new Vector3(currentMoveInput.x, 0, currentMoveInput.y);
transform.Translate(moveDirecrtion * (moveSpeed * Time.deltaTime), Space.Self);
transform.Rotate(0, currentLookInput.x * (rotationSpeed * Time.deltaTime), 0);
}
public void OnMovement(InputValue input)
{
currentMoveInput = input.Get<Vector2>();
}
public void OnLook(InputValue input)
{
currentLookInput = input.Get<Vector2>();
}
}
``