Unity - 获取输入动作值

问题描述 投票:0回答:1

Unity 有一个新的输入系统,但文档充其量是伪劣的,非常混乱并且根本不直接。

如何简单地读取我的输入操作值?我添加了适当的操作设置和代码。 enter image description here

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

public class S_PlayerInputs : MonoBehaviour
{
public PlayerInput playerInput;
public GameObject ownPlayer;
Rigidbody2D rigiBody;
Vector2 moveDirection = Vector2.zero;

// Start is called before the first frame update
void Start()
{
    rigiBody = ownPlayer.GetComponent<Rigidbody2D>();
    Debug.Log(playerInput.currentActionMap);
    playerInput = GetComponent<PlayerInput>();
}

// Update is called once per frame
void FixedUpdate()
{
    Debug.Log(playerInput.Movement.ReadValue<Vector>);
}

void OnJump()
{
    // Jump !!
    rigiBody.velocity = new Vector2(0, 10);
    Debug.Log("Player jumped!");


}

void OnMovement()
{
    //Debug.Log("A or D pressed");
    //moveDirection = playerInput.ReadValue<>;
}
}

做一个简单的

    Debug.Log(playerInput.Movement.ReadValue<Vector>);

没用。跳转很容易理解,但我需要实时读取 X 轴值。

unity3d input
1个回答
0
投票

以下方法是阅读和确定方法两种模式下输入动作的最佳使用方法

private IA_Main playerInput;
void Start()
{
    playerInput = new IA_Main();
    playerInput.Enable(); // Input Action Initializing..

    playerInput.Character.Jump.performed += OnJump; // Jump initializing..
}

考虑一个带有

CallbackContext
参数的方法来跳转。

void OnJump(InputAction.CallbackContext context)
{
    // On Jump..
}

要读取值,只需将其类型视为

float
.

void Update()
{
    var moveAxis = playerInput.Character.Movement.ReadValue<float>();
    Debug.Log(moveAxis);
}

生成输入操作 C# 代码

单击指定密钥的文件,并确保勾选生成 C# 类。 (InputMaster 与我在项目中命名的 IA_Main 相同。)


© www.soinside.com 2019 - 2024. All rights reserved.