Skip to content
Flecs v4.1
queries/with

  • C++

    View on GitHub

    1#include <with.h>
    2#include <iostream>
    3
    4struct Position {
    5 double x, y;
    6};
    7
    8struct Npc { };
    9
    10int main(int, char *[]) {
    11 flecs::world ecs;
    12
    13 // Create a query for Position, Npc. By adding the Npc component using the
    14 // "with" method, the component is not a part of the query type, and as a
    15 // result does not become part of the function signatures of each and iter.
    16 // This is useful for things like tags, which because they don't have a
    17 // value are less useful to pass to the each/iter functions as argument.
    18 flecs::query<Position> q = ecs.query_builder<Position>()
    19 .with<Npc>()
    20 .build();
    21
    22 // Create a few test entities for the Position, Npc query
    23 ecs.entity("e1")
    24 .set<Position>({10, 20})
    25 .add<Npc>();
    26
    27 ecs.entity("e2")
    28 .set<Position>({10, 20})
    29 .add<Npc>();
    30
    31 // This entity will not match as it does not have Position, Npc
    32 ecs.entity("e3")
    33 .set<Position>({10, 20});
    34
    35
    36 // Note how the Npc tag is not part of the each signature
    37 q.each([](flecs::entity e, Position& p) {
    38 std::cout << e.name() << ": {" << p.x << ", " << p.y << "}\n";
    39 });
    40
    41 // Output:
    42 // e1: {10, 20}
    43 // e2: {10, 20}
    44}
    flecs::query_builder< Comps... > query_builder(Args &&... args) const
    Create a query builder.
    Definition impl.hpp:342
    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
    void each(Func &&func) const
    Each iterator.
    Definition iterable.hpp:37
    Typed query.
    Definition impl.hpp:271
    The world.
    Definition world.hpp:129