Click or drag to resize
DigitalRuneHow To: Setup and Run a Simulation

This section explains how setup and run a basic physics simulation.

This topic contains the following sections:

Add DigitalRune namespaces

The following example will use types from DigitalRune Mathematics, Geometry and Physics. The following namespaces must be imported for this example at the beginning of the source code files:

C#
using DigitalRune.Geometry;
using DigitalRune.Geometry.Shapes;
using DigitalRune.Mathematics.Algebra;
using DigitalRune.Physics;
using DigitalRune.Physics.ForceEffects;
Setup simulation

Here is a simple example that shows how to setup the simulation and how to add rigid bodies. The simulation is configured with two force effects: gravity and damping. These force effects are necessary for most scenarios.

The basic setup:

C#
Simulation mySimulation = new Simulation();

// Add a gravity force that pulls objects to the ground.
mySimulation.ForceEffects.Add(new Gravity());

// Add a damping effect that models air resistance and slows objects.
mySimulation.ForceEffects.Add(new Damping());

// Add a ground plane.
RigidBody ground = new RigidBody(new PlaneShape(Vector3F.UnitY, 0))
{
  Name = "GroundPlane",
  Pose = Pose.Identity,
  MotionType = MotionType.Static,  // Ground plane should not move.
};
mySimulation.RigidBodies.Add(ground);

// Add a box above the ground with a random orientation.
RigidBody cube = new RigidBody(new BoxShape(1, 1, 1))
{
  Name = "Cube",
  Pose = new Pose(new Vector3F(0, 2, 0), RandomHelper.Random.NextQuaternionF()),
};
mySimulation.RigidBodies.Add(cube);
Run simulation

In each frame of the game, the simulation must be updated by calling following method (usually with 60 fps):

C#
// Advance the simulation.
// deltaTime is the elapsed time since the last simulation update.
mySimulation.Update(deltaTime);

In between updates you can manipulate the simulation in a variety of ways. For example, you can