This guide will help you get started with Coyote ECS in your Zig project.
git clone --recursive https://github.com/linuxy/coyote-ecs.git
build.zig.zon
:
.{
.name = "your-project",
.version = "0.1.0",
.dependencies = .{
.coyote_ecs = .{
.url = "https://github.com/linuxy/coyote-ecs/archive/main.tar.gz",
.hash = "your-hash-here",
},
},
}
build.zig
:
const coyote_ecs = b.dependency("coyote_ecs", .{
.target = target,
.optimize = optimize,
});
First, define your components in a container:
const std = @import("std");
const ecs = @import("coyote-ecs");
pub const Components = struct {
pub const Position = struct {
x: f32 = 0,
y: f32 = 0,
};
pub const Velocity = struct {
x: f32 = 0,
y: f32 = 0,
};
};
Create a world to manage your entities and components:
var world = try World.create();
defer world.deinit();
// Create an entity
var entity = try world.entities.create();
// Create components
var position = try world.components.create(Components.Position);
var velocity = try world.components.create(Components.Velocity);
// Attach components to the entity
try entity.attach(position, Components.Position{ .x = 0, .y = 0 });
try entity.attach(velocity, Components.Velocity{ .x = 1, .y = 1 });
Systems are functions that operate on entities with specific components:
pub fn UpdatePosition(world: *World) void {
var it = world.entities.iteratorFilter(Components.Position);
while(it.next()) |entity| {
if(entity.getOneComponent(Components.Velocity)) |velocity| {
var pos = entity.getOneComponent(Components.Position).?;
pos.x += velocity.x;
pos.y += velocity.y;
}
}
}
try Systems.run(UpdatePosition, .{world});
var it = world.components.iteratorFilter(Components.Position);
while(it.next()) |component| {
// Work with the component
}
var it = world.entities.iteratorFilter(Components.Position);
while(it.next()) |entity| {
if(entity.getOneComponent(Components.Velocity)) |velocity| {
// Entity has both Position and Velocity components
}
}
// Create
var component = try world.components.create(Components.Position);
// Attach
try entity.attach(component, Components.Position{ .x = 0, .y = 0 });
// Detach
entity.detach(component);
// Destroy
component.destroy();