简体   繁体   中英

How to put a time limit on a method in c#

I want my player to give a speed boost for a few seconds. When it collects 4 items (paintCount = 4), the player gets a movement speed boost for a short period of time. How do I code this time that my player moves faster?

I'm using c# and 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;
     }

  }
}

A general idea should be:

Add this to the script of SimplePlayer0:

float speedBoostTime = 0;

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

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

And modify your code in this way:

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;

    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM