Skip to content
Flecs v4.1
systems/each_w_iter_callback

  • C++

    View on GitHub

    1#include <each_w_iter_callback.h>
    2#include <iostream>
    3
    4// This example is the same as the each example, but in addition also shows how
    5// to get access to the flecs::iter object. Flecs iterators provide access to a
    6// lot of information about the currently iterated result, such as the matched
    7// entities, table, component ids, whether fields are set or not and more.
    8
    9struct Position {
    10 double x, y;
    11};
    12
    13struct Velocity {
    14 double x, y;
    15};
    16
    17int main(int, char *[]) {
    18 flecs::world ecs;
    19
    20 flecs::system s = ecs.system<Position, const Velocity>()
    21 // Arguments passed to each match components passed to system
    22 .each([](flecs::iter& it, size_t row, Position& p, const Velocity& v) {
    23 flecs::entity e = it.entity(row);
    24 p.x += v.x;
    25 p.y += v.y;
    26 std::cout << e.name() << ": {" << p.x << ", " << p.y << "}\n";
    27 });
    28
    29 // Create a few test entities for a Position, Velocity query
    30 ecs.entity("e1")
    31 .set<Position>({10, 20})
    32 .set<Velocity>({1, 2});
    33
    34 ecs.entity("e2")
    35 .set<Position>({10, 20})
    36 .set<Velocity>({3, 4});
    37
    38 // This entity will not match as it does not have Position, Velocity
    39 ecs.entity("e3")
    40 .set<Position>({10, 20});
    41
    42 // Run the system
    43 s.run();
    44
    45 // Output
    46 // e1: {11, 22}
    47 // e2: {13, 24}
    48}
    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
    flecs::string_view name() const
    Return the entity name.
    Entity.
    Definition entity.hpp:30
    Class for iterating over query results.
    Definition iter.hpp:68
    flecs::entity entity(size_t row) const
    Obtain a mutable handle to the entity being iterated over.
    Definition iter.hpp:36
    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.