Mad*_*Pea 0 c# unity-game-engine
我正在Unity中开展2D游戏.游戏限制为60秒.我想要一个定时炸弹,当玩家击中炸弹时会导致时间缩短.
在我的脚本中,我有一个名为的布尔值,"hitDetect"
我使用一个Coroutine()
倒计时.
当玩家击中炸弹时我试图将炸弹推到右侧,然后用这些代码检查碰撞是否发生:
void OnCollisionEnter2D(Collision2D bombcol)
{
if(bombcol.gameObject.tag == "Enemy")
{
bombcol.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.right * hitForce);
}
hitDetect = true;
}
Run Code Online (Sandbox Code Playgroud)
这是我的Coroutine()
功能,它让我有一个成功限制为60秒的游戏,除了时间惩罚:
IEnumerator LoseTime()
{
while (true) {
yield return new WaitForSeconds (1);
timeLeft--;
if (hitDetect == true)
{
timeLeft= timeLeft - 5;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还在"hitDetect"
开始体中将其设置为false.
void Start ()
{
StartCoroutine("LoseTime");
hitDetect = false;
}
Run Code Online (Sandbox Code Playgroud)
但是,这些方法并没有让我获得成功.当玩家击中炸弹时,时间惩罚不起作用.我的错误在哪里?你会推荐什么?
我建议计算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?
}
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,如果由碰撞hitDetect
设置true
,您的时间将减去惩罚值一次.
希望这可以帮助!