← Tutorials

Physics playground

This tutorial takes about twenty minutes. You need Turian installed and the first tutorial done: you should know how to create a project, attach a script to a node and press F5.

Physics comes from two bricks. org.mass4.turian.physics provides the components (rigidbodies, colliders, joints, queries) and org.mass4.turian.physics.bepu is the backend that actually moves things. You need both.

1. Create a project

turian-cli new PhysicsPlayground
turian-studio --project PhysicsPlayground

The starter scene, Assets/scene-01.prefab, has a Camera, a Light and a Box. Open it by double-clicking it in the Assets panel.

The Box has an empty Mesh component and no model, so it draws a multicolored placeholder instead of a cube. Step 3 replaces it.

2. Install the physics bricks

Bricks are listed in Bricks/manifest.json inside the project. You can add them in either of two ways.

In Studio, open Project → Bricks… and add org.mass4.turian.physics and org.mass4.turian.physics.bepu.

From a terminal, run:

turian-cli brick add org.mass4.turian.physics --project PhysicsPlayground
turian-cli brick add org.mass4.turian.physics.bepu --project PhysicsPlayground
turian-cli brick list --project PhysicsPlayground

The list shows both bricks with their versions. If brick add cannot find them in the registry, add each one from a local checkout instead, with the source after the id:

turian-cli brick add org.mass4.turian.physics file:/path/to/org.mass4.turian.physics --project PhysicsPlayground

The physics bricks change nothing in the scene until you add their components, so the Box does not move yet.

3. Make a floor and a falling box

The Box needs a visible cube first. Copy Cube.gltf, Cube.bin, Cube.gltf.meta and Cube.bin.meta from example-12-physics/Assets/Models into your project's Assets folder. Turian imports them, and the .meta files keep the model's id.

Select Box, remove its Mesh component, and add Rendering → Model. Set its Model slot to Cube. The Box is now a cube.

Select Box in the Scene Tree and press D to duplicate it. Rename the copy Floor with F2. In the Inspector, set the Floor's Position to 0, 0, 0 and its Scale to 10, 0.5, 10, which turns the cube into a wide slab. Then set the original Box's Position to 0, 5, 0.

Select Floor and click Add Component, then choose Physics → Box Collider. The floor has a collider but no rigidbody, so it stays where it is.

Select Box and add two components: Physics → Rigidbody and Physics → Box Collider. A rigidbody makes a node move under gravity, and its collider decides what it touches.

Save with Ctrl+S and press F5. The box falls, lands on the floor and stops. Press F5 again to stop.

4. Make a pile

Select Box and press D to duplicate it, twice. Set the copies' Position to something like 0.3, 7, 0 and -0.2, 9, 0.1 so they fall onto the box below.

The floor with three cubes stacked above it, before Play starts.

Press F5: the boxes land on each other and come to rest.

The three cubes resting in a pile on the floor during Play.

Gravity is -9.81 m/s² by default. To change it, create Settings → Physics from the Assets panel's right-click menu, and edit Gravity there.

5. Push a body from a script

Create Assets/Kick.cs in your code editor. The new project's Globals.cs already imports Silk.NET.Input, so Key needs no using. The physics types live in Turian.Engine.Physics and need one:

using System.Text.Json.Serialization;
using Turian.Engine.Physics;

namespace Usercode;

/// <summary>Kicks the rigidbody on this node upwards when Space is pressed.</summary>
public sealed class Kick : Component
{
    RigidbodyComponent? body;

    /// <summary>Upward impulse in newton-seconds.</summary>
    public float Strength = 5f;

    /// <summary>The optional player input.</summary>
    [InjectService(Optional = true), JsonIgnore]
    public IInputSource? Input { get; private set; }

    public override void OnStart() => body = Node!.GetComponent<RigidbodyComponent>();

    public override void OnUpdate(float deltaTime)
    {
        if (body is not null && Input?.WasKeyPressed(Key.Space) == true)
        {
            body.AddForce(Vector3.UnitY * Strength, ForceMode.Impulse);
        }
    }
}

Save it, then drag Kick.cs from the Assets panel onto Box. Press F5, click inside the Game view so it receives the keyboard, and press Space. The box jumps. Each press applies one impulse. Escape hands the keyboard back to Studio.

ForceMode.Impulse is an instant push in newton-seconds that scales with the body's mass. ForceMode.Force is a continuous force in newtons, ForceMode.Acceleration a continuous acceleration that ignores mass, and ForceMode.VelocityChange an instant velocity change that ignores mass.

6. Add a ragdoll

A ragdoll is a set of capsule-shaped bodies and joints fitted to a posed skeleton. The helper RagdollBuilder reads the bones you give it and leaves them in place: the physics proxies move and drive the bones. This tutorial uses a three-bone spine so you can see the mechanism. The full version, with arms and legs, is the ragdoll.prefab scene in example-12-physics.

Create the rig in the Scene Tree. Right-click the root and choose New Node, then name it Ragdoll. With Ragdoll selected, choose New Child Node, name it Skeleton and set its Position to 3, 3, 0. With Skeleton selected, choose New Child Node to build this hierarchy, setting each Position:

Node Parent Position
Hips Skeleton 0, 0, 0
Chest Hips 0, 0.45, 0
Head Chest 0, 0.55, 0
Crown Head 0, 0.35, 0

Crown only marks where the head ends. The bones are empty nodes, so the ragdoll is visible as capsule gizmos in the Scene view. See Gizmos.

Create Assets/Ragdoll.cs:

using System.Text.Json.Serialization;
using Turian.Engine.Physics;

namespace Usercode;

/// <summary>Turns a three-bone spine into a ragdoll. Space switches between the posed pose and physics.</summary>
public sealed class Ragdoll : Component
{
    RagdollRig? rig;

    /// <summary>The root that holds the bones.</summary>
    public Node? Skeleton;

    /// <summary>The bones, from the hips up.</summary>
    public Node? Hips;
    public Node? Chest;
    public Node? Head;
    public Node? Crown;

    /// <summary>The optional player input.</summary>
    [InjectService(Optional = true), JsonIgnore]
    public IInputSource? Input { get; private set; }

    public override void OnStart()
    {
        var bones = new List<RagdollBone>
        {
            new() { Bone = Hips!, EndBone = Chest, MassWeight = 8, Radius = 0.16f },
            new() { Bone = Chest!, EndBone = Head, MassWeight = 10, Radius = 0.18f },
            new() { Bone = Head!, EndBone = Crown, MassWeight = 4, Radius = 0.14f },
        };
        rig = RagdollBuilder.Create(Skeleton!, bones, new RagdollSettings { TotalMass = 70, SwingLimit = 50 });
    }

    public override void OnUpdate(float deltaTime)
    {
        if (rig is null || Input is null)
        {
            return;
        }

        if (Input.WasKeyPressed(Key.Space))
        {
            rig.SetKinematic(!rig.IsKinematic);
        }

        if (Input.WasKeyPressed(Key.I) && !rig.IsKinematic)
        {
            rig.Parts[0].Body.AddForce(new Vector3(0, 0, 20), ForceMode.Impulse);
        }
    }

    public override void OnDestroy() => rig?.Dispose();
}

Save it and drag Ragdoll.cs onto Ragdoll, the parent of the skeleton, not onto Skeleton itself. The builder adds the physics nodes beside the skeleton when the scene starts. A component on Skeleton would make Play stop with "The children changed during enumeration", because Skeleton is a child of the root that is still being started.

In the Inspector, drag each bone node onto its slot: Skeleton onto Skeleton, Hips onto Hips, and so on for Chest, Head and Crown. Press F5. The skeleton starts posed and stays still, because a new rig starts in animation mode. Press Space to hand it to physics: it collapses onto the floor. Press I while it is dynamic to push the hips forward, and Space again to return it to the pose.

Next steps

  • Sound and music — import audio, play it from a script and loop background music.
  • Components — the component model behind everything above.
  • Bricks — installing, forking and publishing bricks.
  • Input — rebindable controls and gamepads instead of fixed keys.
  • Play mode — how Play, pause and step work in Studio.

Edit this page