我已经制作了这个脚本来检查玩家和陷阱之间的碰撞并移除玩家hp。它运作完美,但惠普几乎立即下降。我尝试使用协程,但我不知道如何使它工作。
using UnityEngine;
using System.Collections;
using System;
public class hp_loss : MonoBehaviour
{
public float loss_hp = 1;
void OnTriggerStay2D(Collider2D other)
{
GameObject gObj = other.gameObject;
if (gObj.CompareTag("enemy") && hajs.hp > 0)
{
hajs.hp = hajs.hp - loss_hp;
}
}
}
答案 0 :(得分:0)
http://docs.unity3d.com/Manual/Coroutines.html
我怀疑你想要OnTriggerStay2D
,因为它会多次发射。
IEnumerator OnTriggerEnter2D(Collider2D other)
{
yield return new WaitForSeconds(2f);
GameObject gObj = other.gameObject;
if (gObj.CompareTag("enemy") && hajs.hp > 0)
{
hajs.hp = hajs.hp - loss_hp;
}
}
答案 1 :(得分:0)
我会以这种方式去做某事
D
答案 2 :(得分:0)
greendhsde的答案应该做的工作,但只是在你想要在OnTriggerStay2D
函数中完成所有这些工作而不需要更多的函数和更少的代码,这段代码也应该没问题。 decreaseTime
越高,更新的时间越短。如果decreaseTime
设置为2秒,则每2秒更新一次。
float decreaseTime = 0.2f;
float startCounter = 0f;
public float loss_hp = 1;
void OnTriggerStay2D(Collider2D other)
{
//Dont decrease if startCounter < decrease Time
if (startCounter < decreaseTime)
{
startCounter += Time.deltaTime;
return;
}
startCounter = 0; //Reset to 0
//Don't decrease if score is less or equals to 0
if (hajs.hp <=0)
{
return;
}
GameObject gObj = other.gameObject;
if (gObj.CompareTag("enemy"))
{
hajs.hp = hajs.hp - loss_hp;
}
}