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

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

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

 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 input controls
2个回答
0
投票

您可以尝试使用 .AddForce 方法

Unity - AddForce

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

        if (button.isPressed && isGrounded)
        {
            rb.AddForce(transform.up * jumpForce);
        }
    }

在您的情况下,可能需要校准“jumpForce”值以获得所需的输出。


0
投票

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

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.