public static bool Simulate (float step);

参数

step推进物理模拟的时间。

返回

bool 是否正在运行模拟。物理回调期间无法成功运行模拟。

描述

在场景中进行物理模拟。

调用 Physics2D.Simulate 不会导致调用 FixedUpdate。无论自动模拟关闭与否以及您何时调用 Physics2D.Simulate,都仍将以 Time.fixedDeltaTime 定义的速率调用 MonoBehaviour.FixedUpdate

注意,如果将与帧率相关的步长值(例如 Time.deltaTime)传递给物理引擎,则由于可能出现的不可预测的帧率波动,您的模拟将是不确定的。要获得确定性的物理结果,每次调用 Physics2D.Simulate 时都应该向其传递一个固定的步长值。

即使不处于播放模式下,也可以在 Editor 中调用 Physics2D.Simulate,但要务必小心,因为这将导致模拟移动附加了 Rigidbody2D 组件的游戏对象。在非播放模式下的 Editor 中进行模拟时,将对所有物理组件(包括 Rigidbody2DCollider2DJoint2DEffector2D)进行完整的模拟,并会生成接触点。但是,不会通过标准脚本回调来报告接触点。这是一种安全措施,可防止回调删除场景中的对象(这是一种不可撤销的操作)。

另请参阅:Physics2D.autoSimulation

下面是一个基本模拟示例,它实现了在自动模拟模式下完成的操作。

using UnityEngine;

public class BasicSimulation : MonoBehaviour { private float timer;

void Update() { if (Physics2D.autoSimulation) return; // do nothing if the automatic simulation is enabled

timer += Time.deltaTime;

// Catch up with the game time. // Advance the physics simulation in portions of Time.fixedDeltaTime // Note that generally, we don't want to pass variable delta to Simulate as that leads to unstable results. while (timer >= Time.fixedDeltaTime) { timer -= Time.fixedDeltaTime; Physics2D.Simulate(Time.fixedDeltaTime); }

// Here you can access the transforms state right after the simulation, if needed... } }