Tutorials
Tutorials
A first 3D game
Make a small 3D game from start to finish: a ball you roll with the keyboard or a gamepad, a camera that follows it, and gems that spin until you roll into them. Along the way you meet the pieces every Abyss game is made of: entities placed in a scene, components that hold their data, systems that move them, prefabs, 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
- In the Hub, click Projects, then New Project.
- Pick the 3D Game template.
- Name the project GemHunt, and click Create Project.
The editor opens on the Main scene, with a Main Camera and a Directional Light. The game's C# goes in the namespace GemHunt, after the project's name; the code below uses it.
2. Build the level
- Choose Entity ▸ 3D Object ▸ Plane. It is ten meters square, made at the origin.
- In the Inspector, set its Scale to 3 on X and Z, for a floor thirty meters across.
- Choose Entity ▸ 3D Object ▸ Sphere. In the Hierarchy, press F2 and name it Player. Set its Position Y to 0.5, so it rests on the floor.
- Press Ctrl+S to save the scene.
3. Write the code
The game needs three components, the data its entities carry:
- Player, on the ball: how fast it rolls.
- Gem, on each gem: how fast it spins.
- Follow Player, on the camera: where it sits, relative to the ball.
And four systems, which run every frame: one moves the ball from the input, one keeps the camera behind it, one spins the gems, and one collects the gems the ball touches.
- In the Project panel, open the
scriptsfolder. - Click +, choose Component Script, and name it
GemHunt. The editor makesscripts/GemHunt.cs. - 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<GemHunt.GemHuntPlugin>]
namespace GemHunt;
/// <summary>The ball the player rolls.</summary>[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct Player{ /// <summary>How fast it rolls, in meters a second.</summary> public float Speed = 5f;}
/// <summary>A gem to collect.</summary>[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct Gem{ /// <summary>How fast it spins, in degrees a second.</summary> public float Spin = 90f;}
/// <summary>Keeps a camera where it can see the ball.</summary>[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct FollowPlayer{ /// <summary>Where the camera sits, from the ball.</summary> public Vector3 Offset = new(0f, 6f, 8f);}
/// <summary>Where the ball is this frame, for the systems that follow it.</summary>public struct PlayerSpot{ public Vector3 Position;}
/// <summary>How many gems the ball has collected.</summary>public struct Score{ public int Gems;}
public static partial class GemHuntSystems{ /// <summary>Rolls the ball from the Move action: W, A, S, D, the arrows or a stick.</summary> [AbyssSystem] [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void MovePlayer(ref Transform transform, in Player player, ResMut<PlayerSpot> spot, in SystemContext context) { Vector2 move = context.Input.Vector(Actions.Player.Move); transform.TranslationX += move.X * player.Speed * context.DeltaTime; transform.TranslationZ -= move.Y * player.Speed * context.DeltaTime; // up is away from the camera: -Z spot.Value.Position = new Vector3(transform.TranslationX, transform.TranslationY, transform.TranslationZ); }
/// <summary>Puts the camera at its offset from the ball.</summary> [AbyssSystem] [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Follow(ref Transform transform, in FollowPlayer follow, Res<PlayerSpot> spot) { Vector3 at = spot.Value.Position + follow.Offset; (transform.TranslationX, transform.TranslationY, transform.TranslationZ) = (at.X, at.Y, at.Z); }
/// <summary>Turns each gem about the vertical axis.</summary> [AbyssSystem] [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Spin(ref Transform transform, in Gem gem, in SystemContext context) { float angle = gem.Spin * (MathF.PI / 180f) * context.DeltaTime; var rotation = new Quaternion(transform.RotationX, transform.RotationY, transform.RotationZ, transform.RotationW); rotation = Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * rotation); (transform.RotationX, transform.RotationY, transform.RotationZ, transform.RotationW) = (rotation.X, rotation.Y, rotation.Z, rotation.W); }}
/// <summary>Adds the game's systems, each time the game starts playing.</summary>public sealed class GemHuntPlugin : IPlugin{ public void Build(Schedule schedule) { World world = schedule.World; ComponentType<Transform> transform = world.Transform(); ComponentType<Gem> gem = world.Component<Gem>();
ResourceType<PlayerSpot> spot = world.RegisterResource<PlayerSpot>(); world.InsertResource(spot); ResourceType<Score> score = world.RegisterResource<Score>(); world.InsertResource(score);
// They run in the order they are added: the ball moves first, then what follows it. GemHuntSystems.AddMovePlayer(schedule, transform, world.Component<Player>(), spot); GemHuntSystems.AddFollow(schedule, transform, world.Component<FollowPlayer>(), spot); GemHuntSystems.AddSpin(schedule, transform, gem);
// Collecting removes entities, so this system is written by hand: it needs their ids. schedule.Add("Collect gems", [transform.Read(), gem.Read()], default, [spot.Read(), score.Write()], context => { Vector3 player = context.Resource<PlayerSpot>(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++) { var at = new Vector3(places[i].TranslationX, places[i].TranslationY, places[i].TranslationZ); if (Vector3.Distance(at, player) < 1f) { context.Commands.Despawn(entities[i]); held.Gems++; Log.Info($"Gems collected: {held.Gems}"); } } } }, structural: StructuralAccess.None.AndDespawn); }}- 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.PlayerSpotandScoreare resources: the world holds one of each, 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 anAddmethod for each, which the plugin calls. Actions.Player.Moveis 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. Input actions shows how to add your own.- "Collect gems" is written by hand, since removing an entity needs its id, which the generated systems do not hand out. It despawns through commands, which the engine applies once the frame's systems have run.
Entities, components and systems explains these ideas, and C# in a game every way to write them.
4. Put the components on
- Pick Player in the Hierarchy. In the Inspector, click Add Component, type
Player, and pick it. - Pick Main Camera. Add Follow Player, and set its Rotation X to -35, so it looks down at the ball.
- Press Ctrl+S.
5. Make a gem, and place many
- Choose Entity ▸ 3D Object ▸ Cube, and name it Gem.
- Set its Position to 3, 0.5, 0 and its Scale to 0.4 on all three axes.
- Add the Gem component.
- Drag Gem from the Hierarchy into the Project panel's
assetsfolder. It becomes a prefab,Gem.prefab, and the entity in the scene an instance of it, written in teal. - With the gem picked, press Ctrl+D to duplicate it, and press W and drag the arrows in the Scene panel to move the copy. Make a dozen, spread across the floor. You can also drag
Gem.prefabfrom the Project panel into the Scene panel for each one. - Press Ctrl+S.
Every gem is an instance of the prefab: open Gem.prefab with a double-click, change its Spin, and every gem follows. Scenes and prefabs covers prefabs in full.
6. Play
Press Ctrl+P. Roll the ball with W, A, S and D, the arrow keys, or a gamepad's stick. The camera follows, the gems spin, and each one you roll into disappears while Logs counts it.
Press Ctrl+P again to stop. The scene goes back to how it was before you pressed Play, every gem included. While the game plays, try changing the ball's Speed in the Inspector: it takes effect at once, and is put back when you stop.
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/. Build and run your game explains the platforms and settings.
Where to go from here
- Show the score on screen: UI documents and controls and UI from code.
- Make the ball roll and bounce with physics: Bodies and colliders.
- Give the gems a color: Meshes and materials.
- Add a jump, or your own controls: Input actions.
- Spawn gems from code as the game plays: Instance prefabs from code.
