[英]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.
当它收集4个项目(paintCount = 4)时,玩家会在短时间内获得移动速度提升。 How do I code this time that my player moves faster?
这次我该如何编码,以便播放器移动更快?
I'm using c# and Unity. 我正在使用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;
}
}
}
A general idea should be: 总体思路应该是:
Add this to the script of SimplePlayer0: 将此添加到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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.