对玩家的持续敌人伤害-Unity 2019.1 Beta

时间:2018-12-13 17:06:23

标签: c# unity3d

基本上我有一个敌人和一个玩家。当敌人或玩家撞到对方时,会造成伤害,并造成玩家受伤,从而导致HP损失。但是,一旦接触,它只会损坏一次。我该如何确保在整个碰撞过程中不间断地对玩家造成伤害?

我正在设置布尔变量isTouching,并在接触时将其设置为true。然后设置一会儿循环,这将不断降低播放器的HP。然后使用OnCollisionExit将isTouching设置为false。

private bool isTouching; // determines if the player is 
touching
private void OnCollisionEnter2D(Collision2D collision)
{
    isTouching = true;


        if (collision.gameObject.tag == "Enemy01")
        {
        while (isTouching == true)
        {
            GetComponent<AudioSource>().Play();
            HPBAR.PlayHP -= Random.Range(5, 30);
            if (HPBAR.PlayHP < 0)// Insures player HP bar doesn't read less 
            than zero in GUI TXT
            {
                HPBAR.PlayHP = 0;

            }
            // Debug.Log("Ouch! " + HPBAR.PlayHP + " Left");
            if (HPBAR.PlayHP <= 0 && HPBAR.lives > 0)
            {

                HPBAR.lives--;
                HPBAR.LPfloat--;
                p5.transform.position = spawner.transform.position;
                HPBAR.PlayHP = Random.Range(100, 150);
                // Debug.Log("You're Dead!!! Lives left: " + (HPBAR.lives + 1));

            }
            else if (HPBAR.PlayHP <= 0 && HPBAR.lives <= 0)
            {

                SceneManager.LoadScene("DeathScene");

            }
        }//end of while


        } // of player tag check

}// end of collision enter

private void OnCollisionExit2D(Collision2D collision)
{
    isTouching = false;
}

while循环会冻结我的计算机,所以我不建议您在while循环上运行它。无论如何,我需要知道的是如何实现我想做的事情。如何使敌人不断伤害玩家?例如,如果我跳到敌人的顶部,它将造成一次伤害,然后我就可以绕过他。我想要不间断的伤害,迫使玩家离开或最终死亡。

1 个答案:

答案 0 :(得分:3)

OnCollisionEnter2D用于仅触发发生相同冲突的第一帧。

您要使用OnCollisionStay2D(),它会在发生冲突的每一帧上触发。

此外,摆脱while循环。该方法终止之前,游戏无法更新(包括调用OnCollisionExit2D)。

private void OnCollisionStay2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Enemy01")
    {
        GetComponent<AudioSource>().Play();

        // To take 5 - 30 damage per second:
        HPBAR.PlayHP -= Random.Range(5f,30f) * Time.deltaTime;

        if (HPBAR.PlayHP < 0)// Insures player HP bar doesn't read less than zero in GUI TXT
        {
            HPBAR.PlayHP = 0;

        }
        // Debug.Log("Ouch! " + HPBAR.PlayHP + " Left");
        if (HPBAR.PlayHP <= 0 && HPBAR.lives > 0)
        {
            HPBAR.lives--;
            HPBAR.LPfloat--;
            p5.transform.position = spawner.transform.position;
            HPBAR.PlayHP = Random.Range(100, 150);
            // Debug.Log("You're Dead!!! Lives left: " + (HPBAR.lives + 1));

        }
        else if (HPBAR.PlayHP <= 0 && HPBAR.lives <= 0)
        {
            SceneManager.LoadScene("DeathScene");
        }

    } // of player tag check

}// end of collision stay

private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Enemy01")
    {
        // put "i quit touching the hurty thing" stuff here.
    }
}