简体   繁体   English

Unity 3D:如何停止在空中跳跃

[英]Unity 3D: How to stop being able to jump in the air

I am trying to achieve jumping on a 2d sprite in 3d world.我正在尝试在 3d 世界中实现二维精灵的跳跃。 I can jump fine but I'm able to keep jumping in the air which I do not want.我可以跳得很好,但我可以继续在我不想要的空中跳跃。 I've been trying to find the problem for hours but still cannot come up with a solution.几个小时以来我一直试图找到问题,但仍然无法找到解决方案。

{ 
   public float jumpHeight = 5f;
    public static bool isJumping = false;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && (isJumping == false))
        {
            gameObject.GetComponent<Rigidbody>().AddForce(new Vector2(0f, jumpHeight), ForceMode.Impulse);
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "Ground")
        {
            isJumping = false;
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.collider.tag == "Ground")
        {
            isJumping = true;
        }
    }
}

Am I missing something?我错过了什么吗?

Put a collider as trigger on your 2D object and check if it is colliding with the terrain or ground.在您的 2D object 上放置一个对撞机作为触发器,并检查它是否与地形或地面发生碰撞。 Only then you can jump.只有这样你才能跳。 The same could be done with a Ray which collides with the ground.与地面碰撞的射线也可以这样做。 You dont need to use both just jump OnCollisionStay and thats it您不需要同时使用两者,只需跳转 OnCollisionStay 即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM