Version: 2022.2
LanguageEnglish
  • C#

PhysicsScene2D.Simulate

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Declaration

public bool Simulate(float step);

Parameters

step The time to advance physics by.

Returns

bool Whether the simulation was run or not. Running the simulation during physics callbacks will always fail.

Description

Simulate physics associated with this PhysicsScene.

Calling this method causes the physics to be simulated over the specified step time. Only the physics associated with this PhysicsScene2D will be simulated. If this PhysicsScene2D is not the default physics Scene (see Physics2D.defaultPhysicsScene) then it is associated with a specific Scene and as such, only components added to that Scene are affected when running the simulation.

If you pass frame rate dependent step values (such as Time.deltaTime) to the physics engine, your simulation will be less deterministic because of the unpredictable fluctuations in frame rate that can arise. To achieve more deterministic physics results, you should pass a fixed step value to PhysicsScene2D.Simulate every time you call it.

You can call PhysicsScene2D.Simulate in the Editor outside of play mode, however caution is advised as this will cause the simulation to move GameObjects that have an attached Rigidbody2D component. When simulating in the Editor outside of play mode, a full simulation occurs for all physics components including Rigidbody2D, Collider2D, Joint2D and Effector2D, and contacts are generated. However, contacts are not reported via the standard script callbacks. This is a safety measure to prevent callbacks from deleting objects in the Scene, which is not an undoable operation.

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... } }