2016-03-25 55 views
0

我已经制作了这个脚本,用于检查玩家和陷阱之间的碰撞并移除玩家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

我会去的东西以这种方式

float timer = 0; 
bool timerCheck = false; 
float timerThreshold = 1000; // value you want to wait 

void Update() 
{ 
    if(timerCheck) 
    { 
     timer += Time.deltaTime; 
    } 
    if (timer > timerThreshold) 
    { 
     timer = 0; 
     GameObject gObj = ...; // get player game object using GameObject.FindWithTag for example 

     if (gObj.CompareTag("enemy") && hajs.hp > 0) 
     { 
      hajs.hp = hajs.hp - loss_hp; 
     } 
    } 
} 

void OnCollisionEnter2D(Collider2D col) 
{ 
    timerCheck = true; 
} 

void OnCollisionExit2D(Collider2D col) 
{ 
    timerCheck = false; 
} 
+0

很棒。我略有修改,但想法是相同的 – MiszczTheMaste

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; 
     } 
    } 
+0

当我把它放在while循环中时,它完美地工作,但碰撞后hp也下降了(我的意思是当我离开陷阱时)。没有循环它减少了一次HP。我尝试使用“OnTriggerStay2D”功能,但后来马上被删除。 – MiszczTheMaste

+0

@MiszczTheMaste在你离开陷阱后会减少,因为2秒等待时间可能太长。一旦玩家进入触发器,无论玩家是否离开陷阱,此代码在2秒后在主要部分中触发。很难告诉你想要什么,如果你只是想使用等待,因为陷阱有动画或其他东西,然后设置时间等于动画长度。你不需要while循环。如果您想在陷阱中使用多个HP滴剂,请使用其他答案 –

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; 
    } 
} 
+0

它以奇怪的方式工作。当玩家与陷阱hp碰撞时会减少几个点,然后停止,直到玩家移动,然后再次相同的事情。 – MiszczTheMaste

+0

修改它。将一些代码移到了compareTag之外,并且没有任何其他问题。 – Programmer

相关问题