Unity3D Particle实时粒子,使ParticleSystem不受TimeScale影响

发表于2018-07-16
评论0 4.2k浏览
Unity原生的粒子系统制作的特效,是依赖deltaTime运行的,因此会受到TimeScale的影响。当通过改变TimeScale的方式来使游戏暂停的话,场景内的特效也全部暂停了。这对于游戏场景内的技能、爆炸等效果来说,被暂停是正常的表现,但对于某些UI的特效,实际上是不应该暂停的。比如新手引导的时候,会把游戏暂停在某一个画面,指引玩家点击某一按钮,围绕按钮的流光就不应该跟着游戏本身暂停。

Unity的粒子系统依赖于deltaTime运行,因此可以猜到ParticleSystem类里应该有依赖时间执行粒子生成的函数。经过查询API可以发现如下接口:
    public void Simulate(float t, bool withChildren, bool restart);
    public void Simulate(float t, bool withChildren);
    public void Simulate(float t);

因此,我们可以使用该接口来传入真是的时间变化,使特定的特效在TimeScale为0时依旧正常运行。

将RealTimeParticle.cs挂载到不需要受时间影响的特效上即可。
RealTimeParticle.cs代码如下:
using UnityEngine;
public class RealTimeParticle : MonoBehaviour 
{
	private ParticleSystem _particle;
	private float _deltaTime;
	private float _timeAtLastFrame;
	void Awake() 
	{
		_particle = GetComponent<ParticleSystem>();
	}
	void Update() 
	{
		if (_particle == null) return;
		_deltaTime = Time.realtimeSinceStartup - _timeAtLastFrame;
		_timeAtLastFrame = Time.realtimeSinceStartup;
		if (Mathf.Abs(Time.timeScale) < 1e-6)
		{
			_particle.Simulate(_deltaTime, false, false);
			_particle.Play();
		}
	}
}

以上就是如何确保粒子系统ParticleSystem不受TimeScale影响的方法,希望能对大家有用。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引