From e3ce7b52f22fb2c165bb72ffb763da094f56e6a2 Mon Sep 17 00:00:00 2001 From: copygirl Date: Mon, 26 Feb 2024 16:30:16 +0100 Subject: [PATCH] Improve README example --- README.md | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 0e32114..101ae15 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ This library is still very much work-in-progress and not ready for use. It's ava ```zig const std = @import("std"); + const flecs = @import("flecs-zig-ble"); const Context = flecs.Context(void); const World = Context.World; @@ -26,25 +27,35 @@ pub fn main() !void { const world = try World.init(); defer world.deinit(); + // Register components. _ = try world.component(Position); _ = try world.component(Velocity); - _ = try world.system("Move", move, flecs.c.EcsOnUpdate, "Position, Velocity"); + // Register a system that moves any entity that has a `Position` by `Velocity` each update. + _ = try world.system("Move", move, flecs.c.EcsOnUpdate, "Position, [in] Velocity"); - const e = world.entity(); + // Create an entity with both `Position` and `Velocity` already pre-added. + const e = try world.entity(.{ .name = "Wroom" }, .{ Position, Velocity }); + // However the components aren't initialized, so do that here: e.set(Position, .{ .x = 10, .y = 20 }); e.set(Velocity, .{ .x = 1, .y = 2 }); + // Progress the world, updating it forever. while (world.progress(0.0)) { } } fn move(it: Iter) void { - const pos_field = it.field(Position, 1); - const vel_field = it.field(Velocity, 2); - - for (pos_field, vel_field) |*p, v| { - p.x += v.x; - p.y += v.y; + // Entities that share components are stored in the same table. + // This function will be called for each table that matches the query. + // With `field` we can grab a column from this table as a typed slice. + const pos_col = it.field(Position, 1); + const vel_col = it.field(Velocity, 2); + + // Both columns have the same size, so we can iterate them at the same time. + // Since we want to modify `Position` we can get a pointer to the element. + for (pos_col, vel_col) |*pos, vel| { + pos.x += vel.x * it.deltaTime(); + pos.y += vel.y * it.deltaTime(); } } ```