Skip to content
Flecs v4.1
systems/each_callback

  • C++

    View on GitHub

    1#include <each_callback.h>
    2#include <iostream>
    3
    4// This example shows how to write a system with the each callback, which
    5// provides the easiest API for iterating over matched components.
    6
    7struct Position {
    8 double x, y;
    9};
    10
    11struct Velocity {
    12 double x, y;
    13};
    14
    15int main(int, char *[]) {
    16 flecs::world ecs;
    17
    18 flecs::system s = ecs.system<Position, const Velocity>()
    19 // Arguments passed to each match components passed to system
    20 .each([](Position& p, const Velocity& v) {
    21 p.x += v.x;
    22 p.y += v.y;
    23 std::cout << "{" << p.x << ", " << p.y << "}\n";
    24 });
    25
    26 // Create a few test entities for a Position, Velocity query
    27 ecs.entity("e1")
    28 .set<Position>({10, 20})
    29 .set<Velocity>({1, 2});
    30
    31 ecs.entity("e2")
    32 .set<Position>({10, 20})
    33 .set<Velocity>({3, 4});
    34
    35 // This entity will not match as it does not have Position, Velocity
    36 ecs.entity("e3")
    37 .set<Position>({10, 20});
    38
    39 // Run the system
    40 s.run();
    41
    42 // Output
    43 // {11, 22}
    44 // {13, 24}
    45}
    flecs::system system(flecs::entity e) const
    Upcast an entity to a system.
    Definition impl.hpp:181
    flecs::entity entity(Args &&... args) const
    Create an entity.
    Definition impl.hpp:195
    System.
    Definition impl.hpp:78
    system & run(Func &&func)
    Replace the system's run callback.
    Definition impl.hpp:108
    The world.
    Definition world.hpp:129
    void each(Func &&func) const
    Iterate over all entities with components in the argument list of the function.