簡體   English   中英

如何在C#中對方法設置時間限制

[英]How to put a time limit on a method in c#

我希望我的播放器加快速度幾秒鍾。 當它收集4個項目(paintCount = 4)時,玩家會在短時間內獲得移動速度提升。 這次我該如何編碼,以便播放器移動更快?

我正在使用c#和Unity。

using UnityEngine;
using System.Collections;

public class PowerUp : MonoBehaviour
{
  void OnTriggerEnter2D(Collider2D other)
  {
    if (other.tag == "Player")
    {
      Paintser.SpeedUp();
      Destroy(this.gameObject);
      Paintser.paintCount++;
    }
  }
}



using UnityEngine;
using System.Collections;

public class Paintser : PowerUp
{

  public static int paintCount = 0;
  public int speedBoostTime = 3;

  public static void SpeedUp()
  {
    if (paintCount == 4)
    {

      SimplePlayer0.speed = SimplePlayer0.speed * 2;

      Paintser.paintCount = Paintser.paintCount = 0;

    }
  }
}
using UnityEngine;
using System.Collections;

public class Paintser : PowerUp
{
  public float normalSpeed = 10;
  public static int paintCount = 0;
  public int speedBoostTime = 3;

  public static void SpeedUp(){

      SimplePlayer0.speed = SimplePlayer0.speed * 2;
      Paintser.paintCount = Paintser.paintCount = 0;
      StartCoroutine(duringBoost(speedBoostTime, normalSpeed));
    }

    private static IEnumerator duringBoost(int duration, int newSpeed){
       yield return new WaitForSeconds(duration);
       SimplePlayer0.speed = newSpeed;
     }

  }
}

總體思路應該是:

將此添加到SimplePlayer0的腳本中:

float speedBoostTime = 0;

void SpeedUp()
{
    speed *= 2;
    speedBoostTime = 3; // seconds
}

void Update()
{
    while ( speedBoostTime > 0 )
    {
        speedBoostTime -= Time.deltaTime;
        if ( speedBoostTime <= 0 ) speed /= 2;
    }
}

並以這種方式修改您的代碼:

public class Paintser : PowerUp
{

  public static int paintCount = 0;
  public int speedBoostTime = 3;

  public static void SpeedUp()
  {
    if (paintCount == 4)
    {

      SimplePlayer0.SpeedUp();

      Paintser.paintCount = Paintser.paintCount = 0;

    }
  }
}

暫無
暫無

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

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