Unity 2D角色不会停止跳跃

时间:2019-08-26 20:43:16

标签: c# visual-studio unity3d

好的,所以我更改了代码并添加了新的C#脚本。我检查了箱菌,它们很好。现在的问题是我跳不起来。

这是我在Move2DPlayer中所做的更改

private void Jump()
    {
        if (Input.GetButtonDown("Jump") && isGrounded == true)
        {
          gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        }
    }

这是新的c#,称为“接地”

public class Grounded : MonoBehaviour
{
    GameObject Player;

    private void Start()
    {
        Player = gameObject.transform.parent.gameObject;

    }


    private void Update()
    {

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Ground")
        {
            Player.GetComponent<Move2DPlayer>().isGrounded = true;
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.collider.tag == "Ground")
        {
            Player.GetComponent<Move2DPlayer>().isGrounded = false;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

private void FixedUpdate()
{
    isGrounded = Physics2D.OverlapCircle(rb.position, checkRadius, whatIsGround);
    //Rest of your stuff
}

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }
}

好的,所以我设法得到了一个与此相关的测试项目。如果这对您不起作用,那么我唯一想到的就是您的刚体可能太大,导致OverlapCircle的碰撞检测无法正常工作。确保将checkRadius设置得足够大以实际检测地面。

答案 1 :(得分:0)

您的播放器本身可能具有Collider2D,并且whatIsGround的配置不正确或您的播放器层有误,所以

Physics2D.OverlapCircle(rb.position, checkRadius, whatIsGround);

总是返回true,因为您与播放器本身发生了碰撞。

我测试了您的代码,没有任何更改,它对我有用:

enter image description here


但是,一些性能和其他注意事项:

  • 不要在Debug.LogUpdate中使用FixedUpdate进行开发,这很好,但请确保稍后将其删除!这是非常强烈的表现。

  • 您可以将检查器设置为调试模式。

    enter image description here

    这样,您可以查看私有字段的值,并且应该注意,isGrounded在您的情况下可能始终是true

    enter image description here

  • 仅仅是美化事物,而不是使用somebool == truesomebool == false

  • ,而不是somebool!somebool
相关问题