Version: 2023.2
public bool Simulate (float deltaTime, int simulationLayers= Physics2D.AllLayers);

参数

deltaTime 推进物理模拟的时间。
simulationLayers The Rigidbody2D and Collider2D layers to simulate.

返回

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

描述

进行与此 PhysicsScene 关联的物理模拟。

Calling PhysicsScene2D.Simulate will perform a single simulation step, simulating physics over the specified step time.

By default, All Layers are simulated, however if you specify layers then only the Rigidbody2D will be simulated. Along with this, only contacts for Collider2D on the specified layer(s) will be handled. Finally, only joints or effectors on the specified layer(s) will be handled.

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

NOTE: Calling Physics2D.Simulate does not cause Unity to call FixedUpdate. Unity still calls MonoBehaviour.FixedUpdate at the rate defined by Time.fixedDeltaTime whether automatic simulation is on or off, and regardless of when you call Physics2D.Simulate. Also, if you pass framerate-dependent step values (such as Time.deltaTime) to the physics engine, your simulation will be less deterministic because of the unpredictable fluctuations in framerate that can arise. To achieve more deterministic physics results, you should pass a fixed step value to Physics2D.Simulate every time you call it.

Additional resources: Physics2D.simulationMode and Physics2D.Simulate.

Here is an example of a basic simulation that implements what's being done in the automatic simulation mode.

using UnityEngine;

public class BasicSimulation : MonoBehaviour { public PhysicsScene physicsScene; private float timer;

void Update() { if (!physicsScene.IsValid()) return; // do nothing if the physics Scene is not valid.

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; physicsScene.Simulate(Time.fixedDeltaTime); }

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