2016-03-25 53 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

相關問題