如何在Unity中使用协同程序创建时间惩罚?

时间:2018-06-07 00:04:05

标签: c# unity3d

我正在Unity中开展2D游戏。游戏限制为60秒。我想要一个定时炸弹,当玩家击中炸弹时会导致时间缩短。

在我的脚本中,我有一个名为"hitDetect"的布尔值,我使用Coroutine()进行倒计时。

当玩家击中炸弹时,我试图将炸弹推到右侧,然后检查是否发生了碰撞:

void OnCollisionEnter2D(Collision2D bombcol)
{
    if(bombcol.gameObject.tag == "Enemy")
    {
        bombcol.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.right * hitForce);
    }
    hitDetect = true;
}

这是我的Coroutine()功能,它让我有一个成功限制为60秒的游戏,除了时间惩罚:

IEnumerator LoseTime()
{
    while (true) {
        yield return new WaitForSeconds (1);
        timeLeft--; 
        if (hitDetect == true)
        {
            timeLeft= timeLeft - 5;
        }
    }
}

我还在启动体中将"hitDetect"设置为false。

void Start () 
    {
        StartCoroutine("LoseTime");
        hitDetect = false;
    } 

然而,这些方法并没有让我获得成功。当玩家击中炸弹时,时间惩罚不起作用。我的错误在哪里?你会推荐什么?

1 个答案:

答案 0 :(得分:5)

我建议在Update()函数中计算时间。因此,您可以确定每帧都会观察到hitDetect,如果您在减去惩罚后重置hitDetect,则只会设置一次惩罚。

public bool hitDetect = false;
public float timeLeft = 60.0f;
public float penaltyTime = 5.0f;

void Start(){
    timeLeft = 60.0f;
    hitDetect = false;
}

void Update(){
    timeLeft -= Time.deltaTime;
    if(hitDetect){
        timeLeft -= penaltyTime;

        // reset the hit!
        hitDetect = false;
    }

    if(timeLeft < 0.0f){
        // end game?
    }
}

使用此代码,如果您的碰撞设置了hitDetect true,则会将惩罚值减去一次。

希望这有帮助!