安装插件 Input System

激活插件 Input System,并保存项目(IDE 自动重启)


在 Assert 目录下,新建 Input、Script 子目录

为球体添加 Rigidbody、Player Input 组件


在 Input 目录下,新建 input action 文件,并命名为 InputAction


在 Script 目录下,新建 script 文件,并命名为 PlayerController


绑定 input action 至球体

双击打开、编辑脚本(PlayerController.cs)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float speed = 10; // 公开属性,方便在 IDE 修改速度值
private Rigidbody rb;
private float movementX = 0;
private float movementY = 0;
// 生命周期函数
// 触发时机:物体被加载到场景时
void Start()
{
rb = GetComponent<Rigidbody>();
}
// 生命周期函数
// 触发时机:物体进行物理模拟时
void FixedUpdate()
{
// 组装 3D 向量
Vector3 vector3D = new Vector3(movementX, 0.0f, movementY);
// 为刚体施加力
rb.AddForce(vector3D * speed);
}
// 事件函数,监听移动输入
void OnMove(InputValue movement)
{
Vector2 vector2D = movement.Get<Vector2>();
movementX = vector2D.x;
movementY = vector2D.y;
}
}
绑定脚本至球体

运行项目
IDE 默认移动按键(WSAD / 方向键)

网友评论