c# - 无法找到/理解如何在 Unity 中为我的 PlayerController 脚本使用新输入系统
问题描述
我有这个用于 2D 自上而下游戏的播放器控制器脚本 它使用旧的输入系统,但我想使用较新的输入系统,以便我的游戏可以支持多种输入类型(也因为我想学习如何使用新的输入系统)
我阅读了关于统一的文档但仍然无法理解,我找到了这个文档https://gamedevbeginner.com/input-in-unity-made-easy-complete-guide-to-the-new-system/#input_system_explained但是看在上帝的份上,我仍然无法理解我到底应该做什么以及如何去做
我设置了控制方案(键盘和鼠标和控制器)、动作图(战斗/移动)、动作(上、下、左右) 这是我设置的控件的屏幕截图
我对 Unity 和编程还是有点陌生,如果有人可以帮助我,将不胜感激这一切都令人难以置信的混乱
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float moveSpeed = 5;
[SerializeField]
private Transform movePoint;
[SerializeField]
private LayerMask obstacleMask;
private void Awake()
{
//remove the move point from the player cause I only did that for the sake of organization
movePoint.parent = null;
}
// Update is called once per frame
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, movePoint.position, moveSpeed * Time.deltaTime);
if (Vector2.Distance(transform.position, movePoint.position) <= .5f)
{
if (Mathf.Abs(Input.GetAxisRaw("Horizontal")) == 1)
{
if (!Physics2D.OverlapCircle(movePoint.position + new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f), .2f, obstacleMask))
{
movePoint.position += new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f);
}
}
else if (Mathf.Abs(Input.GetAxisRaw("Vertical")) == 1)
{
if (!Physics2D.OverlapCircle(movePoint.position + new Vector3(0f, Input.GetAxisRaw("Vertical"), 0f), .2f, obstacleMask))
{
movePoint.position += new Vector3(0f, Input.GetAxisRaw("Vertical"), 0f);
}
}
}
}
}
解决方案
使用新输入系统时不能使用 Input 类。您应该在输入操作中定义输入操作并使用它来移动您的对象。
在统一的资产文件夹中,右键单击 => 创建 => 输入操作。然后为移动定义一些动作,如下图:
然后保存它。单击它并在检查器中启用“生成 C# 类”。然后在你的代码中是这样的:
private void Awake()
{
InputActions playerInput = new InputActions();
playerInput.GamePlayPlayer.Move.performed += context => MoveInput(context);
playerInput.Enable();
}
private void MoveInput(InputAction.CallbackContext context)
{
Vector2 input = context.ReadValue<Vector2>();
moveInputData = new Vector3(input.x, 0, input.y);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, movePoint.position, moveSpeed * Time.deltaTime);
if(moveInputData == Vector3.Zero)
return;
if (Vector2.Distance(transform.position, movePoint.position) <= .5f)
{
if (!Physics2D.OverlapCircle(movePoint.position + moveInputData, .2f, obstacleMask))
{
movePoint.position += moveInputData;
}
}
}
我没有测试它,但我认为它应该没问题。
推荐阅读
- python - 将多列数据框更改为单列而不会丢失python中的信息
- laravel-8 - Spatie 媒体库专业版 - 无法解析“@spatie/media-library-pro-vue2”
- scala - 如何在不使用枢轴方法的情况下将列的行旋转/转置到 spark-scala 中的各个列
- mysql - 如何避免 FindAll 条件默认设置为“未定义”
- c# - 如何创建基础 API 项目并在其他 API 项目中使用此端点?
- c# - C# elasticsearch 在多个索引查询上推断文档类型
- python - 在 ubuntu 20.04 LTS 上将文本转为语音听起来很奇怪
- reactjs - 无法使用某些参数链接到 SPO 页面上的 Web 部件
- java - 如何从列表中获取值
并将其存储为双 - unit-testing - 在测试中找不到 RadioListTile