Table of Contents

Basic 2D Scene (Falling Shapes)

The next step after the basic 2D scene: thirty shapes of five kinds and five colours, dropped in a column that topples into a pile. It adds a loop, a list of shapes with a colour each, and a flat material per colour. Bepu physics does the rest. The 3D twin, E01_3D_FallingShapes, drops the same shapes in the same colours.

The Program.cs file shows how to:

  • Creating many 2D primitives in a loop with CreatePrimitive
  • A list of shape types with a colour each
  • Applying a flat material with CreateFlatMaterial
  • Positioning entities so that they fall into a pile
  • Using helpers: SceneSetup2D, AddGrabber

Basic 2D Scene (Falling Shapes)

View on GitHub.

using Stride.CommunityToolkit.Bepu;
using Stride.CommunityToolkit.Engine;
using Stride.CommunityToolkit.Rendering.ProceduralModels;
using Stride.Core.Mathematics;
using Stride.Engine;

const int ShapeCount = 30;

// The shapes to drop, and the colour of each
(Primitive2D Type, Color Colour)[] shapes =
[
    (Primitive2D.Square(), new Color(30, 70, 170)),
    (Primitive2D.Rectangle(), new Color(240, 150, 60)),
    (Primitive2D.Circle(), new Color(235, 100, 80)),
    (Primitive2D.Capsule(), new Color(110, 200, 110)),
    (Primitive2D.Triangle(), new Color(190, 130, 230)),
];

using var game = new Game();

game.Run(new SceneSetup2D().UseBepu(), start: Start);

void Start(Scene rootScene)
{
    // Left mouse grabs any body, drags it and throws it on release
    game.AddGrabber();

    for (var i = 0; i < ShapeCount; i++)
    {
        // Each kind of shape in turn
        var (type, colour) = shapes[i % shapes.Length];

        var entity = game.CreatePrimitive(type, new()
        {
            Material = game.CreateFlatMaterial(colour)
        });

        // One above the other, each a little to one side, so the column topples into a pile
        entity.Transform.Position = new Vector3(0.1f * (i % 3 - 1), 8 + i * 1.5f, 0);
        entity.Scene = rootScene;
    }
}