Skip to content
Flecs v4.1
queries/run_callback

  • C++

    View on GitHub

    1#include <run_callback.h>
    2#include <iostream>
    3
    4// This example shows how to use the run callback, which provides more direct
    5// control over the iteration of a query. It also makes it easier to run code
    6// before and after the iteration.
    7
    8struct Position {
    9 double x, y;
    10};
    11
    12struct Velocity {
    13 double x, y;
    14};
    15
    16int main(int, char *[]) {
    17 flecs::world ecs;
    18
    19 // Create a query for Position, Velocity.
    21 ecs.query<Position, const Velocity>();
    22
    23 // Create a few test entities for a Position, Velocity query
    24 ecs.entity("e1")
    25 .set<Position>({10, 20})
    26 .set<Velocity>({1, 2});
    27
    28 ecs.entity("e2")
    29 .set<Position>({10, 20})
    30 .set<Velocity>({3, 4});
    31
    32 // This entity will not match as it does not have Position, Velocity
    33 ecs.entity("e3")
    34 .set<Position>({10, 20});
    35
    36 // Iterate the query
    37 q.run([](flecs::iter& it) {
    38 std::cout << "Move begin\n";
    39
    40 while (it.next()) {
    41 auto p = it.field<Position>(0);
    42 auto v = it.field<const Velocity>(1);
    43
    44 for (auto i : it) {
    45 flecs::entity e = it.entity(i);
    46 p[i].x += v[i].x;
    47 p[i].y += v[i].y;
    48 std::cout << e.name()
    49 << ": {" << p[i].x << ", " << p[i].y << "}\n";
    50 }
    51 }
    52
    53 std::cout << "Move end\n";
    54 });
    55
    56 // Output
    57 // Move begin
    58 // e1: {11, 22}
    59 // e2: {13, 24}
    60 // Move end
    61}
    conditional_t< sizeof...(Args)==0 &&_::is_sparse_query< Comps... >::value, flecs::sparse_query< Comps... >, flecs::query< Comps... > > query(Args &&... args) const
    Create a query.
    Definition impl.hpp:326
    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
    entity()
    Default constructor.
    Definition entity.hpp:32
    Class for iterating over query results.
    Definition iter.hpp:68
    flecs::field< A > field(int8_t index) const
    Get read-only access to field data.
    Definition iter.hpp:84
    bool next()
    Progress iterator.
    Definition iter.hpp:465
    void run(Func &&func) const
    Run the iterator.
    Definition iterable.hpp:53
    Typed query.
    Definition impl.hpp:271
    The world.
    Definition world.hpp:129