簡體   English   中英

如何在一段時間內更改變量

[英]How to change variable for a certain period of time

如何在Unity3D中更改變量僅持續5秒或直到某個事件? 例如,改變速度:

void Start ()
{
    GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

void Update ()
{
   if (Input.GetKey(KeyCode.W))
   {
       goUp ();
   }
}
public void goUp() {
   GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
}

由於A被按下,物體一直在上升。 如何使對象不是一直上升,而是按下A時的每一幀? 當沒有按下A時,物體的速度會回到零。 我曾經這樣做過:

void Start () {
   GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

void Update () {

   GetComponent<Rigidbody2D> ().velocity = Vector3.zero;

   if (Input.GetKey(KeyCode.A)) {
       goUp ();
   }

}

public void goUp() {
   GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
}

但是這種方法不合理且CPU過載。 另外,我不能使用Input.GetKeyUp(KeyCode.A)或“else”語句作為觸發器。

我會使用x作為屬性,如果它是速度。 我只是psudeo代碼..在你的Update()每個幀你只關心速度在這種情況下所以你只需要調用它。 您不必經常檢查其他值,因為這些值應由其他事件處理。

Property Speed get;set;

    Void APressed()
{
     Speed = 5;
}

Void AReleased()
{
     Speed = 0;
}

對不起,我在5秒后忘記了第二部分..你可以添加這樣的東西,如果Unity支持async關鍵字..你會更新你的A按下看起來像這樣

   Void APressed()
    {
         Speed = 5;
ReduceSpeedAfter5Seconds();
    }


public async Task ReduceSpeedAfter5Seconds()
{
    await Task.Delay(5000);
    Speed = 0;
}

你試過這個嗎?

if (Input.GetKey(KeyCode.A)) {
       goUp ();
   }
else
{
    GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

在Unity / C#中查看CoRoutines: http ://docs.unity3d.com/Manual/Coroutines.html

這可能正是您所需要的。 如果我正確理解你的問題,我在下面放了一些偽代碼。

if (Input.GetKeyDown("a")) {
    goUp();
    StartCoroutine("ReduceSpeedAfter5Seconds");
}

IEnumerator ReduceSpeedAfter5Seconds() {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
        yield return new WaitForSeconds(5.0f);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM