【问题标题】:How do I jump in Unity? (C#) [duplicate]如何在 Unity 中跳转? (C#)[重复]
【发布时间】:2020-07-22 10:41:07
【问题描述】:

我试图让我的播放器在按下空格键时跳跃。我的角色确实会跳跃,但是当我保持空间时,它会一直在空中上升。我确实知道我的代码有什么问题,只是我不知道如何解决它。

这是我的代码:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public Rigidbody rb;

    public float forwardForce = 500f;
    public float sidewaysForce = 500f;
    public float jumpForce = 200f;

    // FixedUpdate is called once per frame
    void FixedUpdate()
    {   

        // Let the player have the ability to move around using wasd keys and jump using the space key
        if (Input.GetKey("w")) 
        {
            rb.AddForce(0, 0, forwardForce * Time.deltaTime);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0,  0);
        }

        if (Input.GetKey("s")) 
        {
            rb.AddForce(0, 0, -forwardForce * Time.deltaTime);
        }

        if (Input.GetKey("d")) 
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
        }

        if (Input.GetKey(KeyCode.Space)) 
        {
            rb.AddForce(0, jumpForce * Time.deltaTime, 0);
        }
        
    }

}

任何建议都会很有帮助。

【问题讨论】:

  • “我知道我的代码有什么问题”——你知道吗?如果是这样,那么你应该在你的帖子中解释你已经知道代码有什么问题。这将帮助其他人以专门针对您需要帮助的部分的方式提供专门针对您正在处理的问题的答案。如果没有这些信息,问题就会变得非常广泛。

标签: c# unity3d


【解决方案1】:

当按住空格键时,您无条件地添加垂直力分量:

if (Input.GetKey(KeyCode.Space)) 
{
    rb.AddForce(0, jumpForce * Time.deltaTime, 0);
}

如果不知道您想要的游戏规则,就不可能确定最好的改变是什么。但一种选择是仅在 Rigidbody 对象当前首先没有垂直速度时才应用跳跃力:

if (rb.velocity.y == 0 && Input.GetKey(KeyCode.Space)) 
{
    rb.AddForce(0, jumpForce * Time.deltaTime, 0);
}

请注意,这可能会在跳跃的顶点留下一个小窗口,让玩家可以再次跳跃。您可以将其保留在(“双跳”)中,也可以不检查速度,而是检查对象的实际位置,并且仅当它位于被认为是可跳跃的表面(例如地面)时才允许跳跃。

【讨论】:

    【解决方案2】:

    我对 Unity 了解不多,但我建议您在这里需要的是 Input.GetKeyUp 而不是 GetKey

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多