我怎样才能让我的角色立足于unity3d



我有一个角色移动的代码,但接地函数永远不会返回null,尽管我检查了一层地面,但它仍然认为要检查与玩家的盒子碰撞器的碰撞,这样我就可以永远跳过

public float jumpVelocity;
private bool keyPressedW;
private bool isGrounded;
private Rigidbody2D rigidbody2d;
private BoxCollider2D boxCollider2d;
void Start()
{
    rigidbody2d = transform.GetComponent<Rigidbody2D>();
    boxCollider2d = transform.GetComponent<BoxCollider2D>();
}
void Update()
{
    if (Input.GetKeyDown(KeyCode.W))
        keyPressedW = true;
    if (IsGrounded())
        isGrounded = true;
    else isGrounded = false;
}
 private void FixedUpdate()
{
    if (keyPressedW && isGrounded)
    {
        rigidbody2d.velocity = Vector2.up * jumpVelocity;
        keyPressedW = false;
    }
}
private bool IsGrounded()
{
   RaycastHit2D raycastHit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, 
   boxCollider2d.bounds.size, 0f, Vector2.down * 0.1f , 
   LayerMask.GetMask("Platform"));
   Debug.Log(raycastHit2d.collider);
   return raycastHit2d.collider != null;
}

您应该使用光线投射,而不是长方体碰撞器。代码应该是这样的:

 void Update()
    {
       
        if (Input.GetKeyDown(KeyCode.W))
            keyPressedW = true;
    }//remove the part that was here.
 private void FixedUpdate()
    {
        
        if (keyPressedW && isGrounded)
        {
            rigidbody2d.velocity = Vector2.up * jumpVelocity;
            keyPressedW = false;
        }
    }
private bool IsGrounded()
    {
       if (Physics2D.Raycast(transform.position, -transform.up, groundDistance, groundMask)
       {
          return true
       }
       return false
    }

最新更新