60 lines
1.4 KiB
C#
60 lines
1.4 KiB
C#
|
using UnityEngine;
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 物理模拟器脚本
|
|||
|
/// </summary>
|
|||
|
public class PhysicsRootScript : MonoBehaviour
|
|||
|
{
|
|||
|
|
|||
|
//保存唯一对象
|
|||
|
private static PhysicsRootScript instance;
|
|||
|
|
|||
|
//累计时间
|
|||
|
private float _timer;
|
|||
|
|
|||
|
//物理模拟的时间,-1:表示每帧只模拟器一次 ,默认的情况可以使用Time.fixedDeltaTime
|
|||
|
public float FixedDeltaTime = -1;
|
|||
|
|
|||
|
private void Start()
|
|||
|
{
|
|||
|
if (instance != null)
|
|||
|
{
|
|||
|
//把原来的给删除掉,使用新的
|
|||
|
Destroy(instance);
|
|||
|
instance = null;
|
|||
|
}
|
|||
|
instance = this;
|
|||
|
}
|
|||
|
|
|||
|
private void Update()
|
|||
|
{
|
|||
|
//如果autoSimulation被设置为enabled,不进行处理
|
|||
|
if (Physics.autoSimulation)
|
|||
|
return;
|
|||
|
|
|||
|
if (FixedDeltaTime <= 0)
|
|||
|
{
|
|||
|
Physics.Simulate(Time.deltaTime);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
_timer += Time.deltaTime;
|
|||
|
while (_timer >= FixedDeltaTime)
|
|||
|
{
|
|||
|
_timer -= FixedDeltaTime;
|
|||
|
Physics.Simulate(FixedDeltaTime);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
//静态函数 启动模拟
|
|||
|
public static void StartSimulate()
|
|||
|
{
|
|||
|
if (instance == null)
|
|||
|
{
|
|||
|
var go = new GameObject("[PhysicsRoot]");
|
|||
|
go.AddComponent<PhysicsRootScript>();
|
|||
|
DontDestroyOnLoad(go);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|