为什么我的角色卡在跳跃动画中?

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

当我按一次空格键后,我的角色总是卡在跳跃动画中。我在网上搜索过,显然是因为它没有注册我的 onGround 功能,我对如何做感到困惑。如有任何帮助,我们将不胜感激!

这是我的代码:

    public Transform GroundCheckTransform;
    public float GroundCheckRadius;
    public LayerMask GroundMask;

    private Vector3 respawnPoint;
    public GameObject deathBarrier;
    public GameObject enemy;
    public int Respawn;

    private Animator anim;

    Rigidbody2D rb;

    void Start()
    {
        anim = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
        respawnPoint = transform.position;
    }

    void Update()
    {
         transform.position += Vector3.right * SpeedValues[(int)CurrentSpeed] * Time.deltaTime;
        
        if(Input.GetKeyDown(KeyCode.Space))
        {
            if (OnGround())
            {
                rb.velocity = Vector2.zero;
                rb.AddForce(Vector2.up * 26f, ForceMode2D.Impulse);
                anim.SetBool("isJumping", false);
            }
            anim.SetBool("isJumping", true);
        }   
    }
    
    void OnTriggerEnter2D(Collider2D collision)
        {
            if(collision.tag == "Barrier")
            {
                transform.position = respawnPoint;
            }
            if (collision.tag == "Enemy")
            {
                transform.position = respawnPoint;
                
            }
            StartCoroutine(WaitBeforeRespawn());

        IEnumerator WaitBeforeRespawn()
        {
            yield return new WaitForSeconds(1);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }

        if(collision.tag == "End")
        {
           this.gameObject.SetActive(false);
        }
    }
    
    bool OnGround()
    {
        return Physics2D.OverlapCircle(GroundCheckTransform.position, GroundCheckRadius, GroundMask);
        
    }

我在这个问题上已经被困了 2 天了,而且我对 Unity 来说还是个新手,所以现在任何帮助都会被应用!

unity-game-engine 2d
1个回答
0
投票

您仅在检查角色是否在地面上并且玩家按住跳跃键后才将动画设置为 false(无论如何,您也会在之后立即将动画设置回 true)。您需要将动画更改移动到不同的条件。我们还应该将内部

OnGround()
检查移至与输入检查相同的条件,因为如果玩家尝试跳到空中,我们不想执行任何操作(或至少在本例中不是):

// Player is trying to jump AND is on floor.
if(Input.GetKeyDown(KeyCode.Space) && OnGround())
    {
        // Jump
        rb.velocity = Vector2.zero;
        rb.AddForce(Vector2.up * 26f, ForceMode2D.Impulse);
        anim.SetBool("isJumping", true);
    }
// Character is Grounded
else if (OnGround())
{
    anim.SetBool("isJumping", false); // Reset animation.
}
© www.soinside.com 2019 - 2024. All rights reserved.