Tutorials

Tutorials

A first 2D game

Make a small 2D game from start to finish: stars fall from the top of the screen, and you catch them with a paddle you move from side to side. Along the way you meet the pieces every Abyss game is made of: sprites placed in a scene, components that hold their data, systems that move them, a prefab the game makes copies of while it plays, and the input actions a new game already has.

It takes about half an hour. You need the Hub and an editor installed (see Install the Hub), and a code editor for C#.

1. Make the project

  1. In the Hub, click Projects, then New Project.
  2. Pick the 2D Game template.
  3. Name the project StarCatcher, and click Create Project.

The editor opens on the Main scene, in the Scene panel's 2D view, with a Main Camera that is a 2D camera. It shows ten units from the bottom of the screen to the top, from -5 to 5, and as many across as the screen's shape allows. The game's C# goes in the namespace StarCatcher, after the project's name; the code below uses it.

2. Write the code

The game needs three components, the data its entities carry:

  • Paddle, on the paddle: how fast it moves.
  • Star, on each star: how fast it falls.
  • Star Spawner, on an entity of its own: which prefab to make stars from, and how often.

And four systems, which run every frame: one moves the paddle from the input, one makes new stars, one moves every star down, and one catches the stars that reach the paddle and removes those that fall past it.

  1. In the Project panel, open the scripts folder.
  2. Click +, choose Component Script, and name it StarCatcher. The editor makes scripts/StarCatcher.cs.
  3. Double-click it to open it in your code editor, and replace what it holds with this:
using System.Numerics;using System.Runtime.CompilerServices;using System.Runtime.InteropServices;using Abyss.Core;
[assembly: AbyssPlugin<StarCatcher.StarCatcherPlugin>]
namespace StarCatcher;
/// <summary>The paddle the player moves.</summary>[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct Paddle{    /// <summary>How fast it moves, in units a second.</summary>    public float Speed = 9f;
    /// <summary>How far it goes from the middle, either way.</summary>    public float Reach = 7f;}
/// <summary>A falling star.</summary>[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct Star{    /// <summary>How fast it falls, in units a second.</summary>    public float Speed = 3f;}
/// <summary>Makes a star now and then, somewhere along the top.</summary>[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct StarSpawner{    /// <summary>The prefab each star is a copy of.</summary>    public PrefabRef Star;
    /// <summary>Seconds between stars.</summary>    public float Every = 0.8f;
    /// <summary>How wide the band is that stars start in.</summary>    public float Width = 14f;
    /// <summary>Seconds since the last star.</summary>    [HideInInspector]    public float Since;}
/// <summary>Where the paddle is this frame.</summary>public struct PaddleSpot{    public Vector2 Position;}
/// <summary>The star prefab, loaded once.</summary>public struct LoadedStar{    public PrefabId Prefab;    public bool Loaded;}
/// <summary>Stars caught and missed.</summary>public struct Score{    public int Caught;    public int Missed;}
public static partial class StarCatcherSystems{    /// <summary>Moves the paddle from the Move action: A and D, the arrows, or a stick.</summary>    [AbyssSystem]    [MethodImpl(MethodImplOptions.AggressiveInlining)]    private static void MovePaddle(ref Transform transform, in Paddle paddle, ResMut<PaddleSpot> spot, in SystemContext context)    {        Vector2 move = context.Input.Vector(Actions.Player.Move);        float x = transform.TranslationX + (move.X * paddle.Speed * context.DeltaTime);        transform.TranslationX = Math.Clamp(x, -paddle.Reach, paddle.Reach);        spot.Value.Position = new Vector2(transform.TranslationX, transform.TranslationY);    }
    /// <summary>Makes a star every so often, from the spawner's prefab.</summary>    [AbyssSystem]    [MethodImpl(MethodImplOptions.AggressiveInlining)]    private static void Spawn(ref StarSpawner spawner, ResMut<LoadedStar> star, in SystemContext context)    {        if (!star.Value.Loaded)        {            star.Value.Prefab = context.Assets.LoadPrefab(spawner.Star);            star.Value.Loaded = true;        }
        spawner.Since += context.DeltaTime;        if (spawner.Since < spawner.Every)        {            return;        }
        spawner.Since = 0f;        float x = (Random.Shared.NextSingle() - 0.5f) * spawner.Width;        context.Commands.Instantiate(star.Value.Prefab, new Vector3(x, 6f, 0f), Quaternion.Identity);    }
    /// <summary>Moves every star down.</summary>    [AbyssSystem]    [MethodImpl(MethodImplOptions.AggressiveInlining)]    private static void Fall(ref Transform transform, in Star star, in SystemContext context)    {        transform.TranslationY -= star.Speed * context.DeltaTime;    }}
/// <summary>Adds the game's systems, each time the game starts playing.</summary>public sealed class StarCatcherPlugin : IPlugin{    public void Build(Schedule schedule)    {        World world = schedule.World;        ComponentType<Transform> transform = world.Transform();        ComponentType<Star> star = world.Component<Star>();
        ResourceType<PaddleSpot> spot = world.RegisterResource<PaddleSpot>();        world.InsertResource(spot);        ResourceType<LoadedStar> loaded = world.RegisterResource<LoadedStar>();        world.InsertResource(loaded);        ResourceType<Score> score = world.RegisterResource<Score>();        world.InsertResource(score);
        StarCatcherSystems.AddMovePaddle(schedule, transform, world.Component<Paddle>(), spot);        StarCatcherSystems.AddSpawn(schedule, world.Component<StarSpawner>(), loaded, structural: StructuralAccess.None.AndInstantiate);        StarCatcherSystems.AddFall(schedule, transform, star);
        // Catching removes entities, so this system is written by hand: it needs their ids.        schedule.Add("Catch stars", [transform.Read(), star.Read()], default, [spot.Read(), score.Write()], context =>        {            Vector2 paddle = context.Resource<PaddleSpot>(0).Value.Position;            ref Score held = ref context.ResourceMut<Score>(1).Value;            foreach (Chunk chunk in context.Chunks)            {                ReadOnlySpan<Transform> places = chunk.GetReadOnlySpan<Transform>(0);                ReadOnlySpan<ulong> entities = chunk.Entities;                for (int i = 0; i < chunk.Count; i++)                {                    float x = places[i].TranslationX;                    float y = places[i].TranslationY;                    if (MathF.Abs(x - paddle.X) < 1.5f && MathF.Abs(y - paddle.Y) < 0.5f)                    {                        context.Commands.Despawn(entities[i]);                        held.Caught++;                        Log.Info($"Caught {held.Caught}, missed {held.Missed}");                    }                    else if (y < -6f)                    {                        context.Commands.Despawn(entities[i]);                        held.Missed++;                        Log.Info($"Caught {held.Caught}, missed {held.Missed}");                    }                }            }        }, structural: StructuralAccess.None.AndDespawn);    }}
  1. Save the file and switch back to the editor. It builds the scripts on its own; the Logs panel shows any error.

What the code does:

  • [AbyssComponent] makes each struct a component: the Inspector shows its fields, and the scene saves them. A field's initializer is the value it starts with, and [HideInInspector] keeps a field the code uses out of the Inspector.
  • PrefabRef is a slot in the Inspector that takes a prefab. The spawner loads it once and keeps the loaded prefab in a resource, LoadedStar: the world holds one of each resource, for systems to share.
  • Each [AbyssSystem] method is a system. Its parameters are what it works on: it runs once for every entity that has the components it names, and reads or writes the resources it names. The build writes an Add method for each, which the plugin calls.
  • context.Commands.Instantiate makes a copy of the prefab, and context.Commands.Despawn removes an entity. Both are commands, which the engine applies once the frame's systems have run, so each system says what it does to the world: AndInstantiate, AndDespawn.
  • Actions.Player.Move is an input action every new game has. It reads W, A, S and D, the arrow keys, and a gamepad's left stick, as a direction; the paddle uses its X.

Entities, components and systems explains these ideas, and C# in a game every way to write them.

3. Make the paddle

  1. Choose Entity ▸ 2D Object ▸ Square. It is one unit across, made at the middle of the screen.
  2. Press F2 in the Hierarchy and name it Paddle.
  3. In the Inspector, set its Position Y to -4 and its Scale X to 3 and Scale Y to 0.4.
  4. Click Add Component, type Paddle, and pick it.

4. Make the star, as a prefab

  1. Choose Entity ▸ 2D Object ▸ Circle, and name it Star.
  2. Set its Scale to 0.5 on X and Y, and in its Sprite section, set Color to a yellow.
  3. Add the Star component.
  4. Drag Star from the Hierarchy into the Project panel's assets folder. It becomes a prefab, Star.prefab.
  5. Delete the Star entity from the scene (Delete): the game makes its own stars from the prefab.

5. Make the spawner

  1. Choose Entity ▸ Create Empty (Ctrl+Shift+N), and name it Star Spawner.
  2. Add the Star Spawner component.
  3. Drag Star.prefab from the Project panel onto its Star slot.
  4. Press Ctrl+S to save the scene.

6. Play

Press Ctrl+P. Stars fall from the top. Move the paddle with A and D, the arrow keys, or a gamepad's stick, and catch them. Logs keeps the count of stars caught and missed.

Press Ctrl+P again to stop. The scene goes back to how it was before you pressed Play: the stars the game made are gone. While the game plays, try changing the spawner's Every or the paddle's Speed in the Inspector: it takes effect at once, and is put back when you stop.

To change every star at once, double-click Star.prefab to open it on its own, and change its Speed or Color. The stars made after that are made from the prefab as it is.

7. Build it

Choose File ▸ Build Settings. The Main scene is already in the build. Click Build, and the editor writes a game you can run without the editor under builds/. For a game that plays in a browser, pick the web platform there; see Build and run your game.

Where to go from here