使用 Unity 的新输入系统,如何根据按下跳转按钮的时间长短应用跳转高度?

Using Unity's new input system, how do I apply a jump height based on how long the jump button is pressed?

提问人:Lordvanan 提问时间:10/21/2023 更新时间:10/22/2023 访问量:41

问:

我正在使用新的输入系统,我现在有一个简单的代码用于跳转:

 void OnJump(InputValue button)
    {
        isGrounded = groundCheck.IsTouchingLayers(LayerMask.GetMask("Ground"));

        if (button.isPressed && isGrounded)
        {
            rb.velocity += new Vector2 (0f, jumpForce);
        }
    }

这可行,但它非常僵硬,每次按下按钮时都会被卡在相同的高度上。

我该怎么做才能让玩家根据按下按钮的时间长短跳高?

下面是一些上下文的整个播放器控制器:

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

public class PlayerController : MonoBehaviour
{
    [SerializeField] float moveSpeed = 10f;
    [SerializeField] float jumpForce = 15f;
    [SerializeField] Rigidbody2D rb;
    [SerializeField] Collider2D groundCheck;

    Vector2 moveInput;
    bool isMoving;
    bool isGrounded;

    
    void Update()
    {
        Run();
        Flip();
    }

    void OnMove(InputValue value)
    {
        moveInput = value.Get<Vector2>();
    }

    void OnJump(InputValue button)
    {
        isGrounded = groundCheck.IsTouchingLayers(LayerMask.GetMask("Ground"));

        if (button.isPressed && isGrounded)
        {
            rb.velocity += new Vector2 (0f, jumpForce);
        }
    }

    void Run()
    {
        Vector2 runVelocity = new Vector2(moveInput.x * moveSpeed, rb.velocity.y);
        rb.velocity = runVelocity;
    }

    void Flip()
    {
        isMoving = Mathf.Abs(rb.velocity.x) > Mathf.Epsilon;

        if (isMoving)
        {
            transform.localScale = new Vector2(Mathf.Sign(rb.velocity.x), 1f);
        }
    }
}

我是初学者,所以我尝试的任何事情都可能根本没有正确实现。

我通读了关于刚体物理的统一手册,并尝试使用 AddForce 而不是使用新的 Vector2 来计算速度。我不确定我是否正确应用了它。

C# Unity-Game-Engine 输入 控件

评论


答:

0赞 Lordvanan 10/22/2023 #1

我花了一整天的时间,但我终于找到了可行的解决方案。

public void OnJump(InputAction.CallbackContext context)
{
    bool jumpButtonPressed = context.performed;
    bool jumpButtonReleased = context.canceled;
    
    if (jumpButtonPressed && isGrounded)
    {
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }

    if (jumpButtonReleased && rb.velocity.y > 0f)
    {
        rb.velocity = new Vector2 (rb.velocity.x, 0f);
    }
}