在我的代码中,当玩家进入触发器时,我正在调用慢动作功能,但我希望此功能在1秒后停止,我尝试了以下代码,但慢动作不起作用。你有什么主意吗?
播放器脚本:
public Rigidbody Ball;
public float Speed = 50f;
public TimeManager timeManager;
bool SlowOn;
bool ClickDone = false;
// Use this for initialization
void Start () {
StartCoroutine(SlowOff());
}
// Update is called once per frame
void FixedUpdate () {
if (!ClickDone){
if (Input.GetMouseButton (0)) {
ClickDone = true;
Ball.velocity = transform.forward * Speed;
}
}
}
private void OnTriggerEnter (Collider other) {
if(other.gameObject.CompareTag ("SlowMotionArea")) {
if (SlowOn) {
timeManager.DoSlowMotion();
}
}
}
IEnumerator SlowOff () {
yield return new WaitForSeconds(2.0f);
SlowOn = false;
}
TimeManager脚本:
public float SlowDownFactor = 0.05f;
public float SlowdownLength = 2f;
public void DoSlowMotion () {
Time.timeScale = SlowDownFactor;
Time.fixedDeltaTime = 0.02f * Time.timeScale ;
}
答案 0 :(得分:0)
您的代码有一些问题
您永远不会将SlowOn
设置为true
,所以您的行
timeManager.DoSlowMotion();
从不执行。您应该在代码中的某个位置调用
SlowOn = true;
我正在猜测,但看来您想使用该布尔字词来防止多次调用timeManager.DoSlowMotion()
?在这种情况下,它应该类似于
if(!SlowOn)
{
timeManager.DoSlowMotion();
SlowOn = true;
}
为什么要在StartCoroutine(SlowOff());
方法中调用Start()
?
我想您应该删除该行并将其放在
之后timeManager.DoSlowMotion();
StartCoroutine(SlowOff());
因此,协程程序每次启动SlowMotion都会启动。
仅停止设置SlowOn = false
不足以让SlowMotion停止。
在您的TimeManager
中,您应该存储原始的TimeScale并通过第二种方法将其重置:
public float SlowDownFactor = 0.05f;
public float SlowdownLength = 2f;
private float originalTimeScale;
private float originalFixedDeltaTime;
public void DoSlowMotion () {
// before changing store current values
originalTimeScale = Time.timeScale;
originalFixedDeltaTime = Time.fixedDeltaTime;
Time.timeScale = SlowDownFactor;
Time.fixedDeltaTime = 0.02f * Time.timeScale ;
}
public void ResetTimeScales()
{
Time.timeScale = originalTimeScale;
Time.fixedDeltaTime = originalFixedDeltaTime;
}
然后您还必须从播放器调用该ResetTimeScales
方法
IEnumerator SlowOff () {
yield return new WaitForSeconds(2.0f);
timeManager.ResetTimeScales();
SlowOn = false;
}
我想你知道
yield return new WaitForSeconds(2.0f);
还将受到更改的时间刻度的影响,因此您的慢动作现在将比预期的2
秒长,即2 / SlowDownFactor
= 40
!
您可以通过使用Time.unscaledDeltaTime
这样的倒计时来避免这种情况
private IEnumerator SlowOff()
{
// since your title actually claims you want to reset after 1 second
float timer = 1;
while (timer > 0)
{
timer -= Time.unscaledDeltaTime;
yield return null;
}
timeManager.ResetTimeScales();
SlowDown = false;
}