首页 > 解决方案 > 无法找到/理解如何在 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);
                }

            }
        }
    }
}

标签: c#unity3d

解决方案


使用新输入系统时不能使用 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;
        }
    }
}

我没有测试它,但我认为它应该没问题。


推荐阅读