jecs/docs/api/world.md
2024-07-30 15:41:28 +02:00

2.5 KiB

World

A World contains entities which have components. The World is queryable and can be used to get entities with a specific set of components.

Functions

new()

function World.new(): World

Creates a new world.

Example: ::: code-group

local world = jecs.World.new()
import { World } from "@rbxts/jecs";

const world = new World();

:::

entity()

function World:entity(): Entity -- The new entit.

Creates a new entity.

Example: ::: code-group

local entity = world:entity()
const entity = world.entity();

:: :

component()

function World:component<T>(): Entity<T> -- The new componen.

Creates a new component.

Example: ::: code-group

local Health = world:component() :: jecs.Entity<number>
const Health = world.component<number>();

:::

::: info You should use this when creating components.

For example, a Health type should be created using this. :::

get()

function World:get(
    entity: Entity, -- The entity
    ...: Entity<T> -- The types to fetch
): ... -- Returns the component data in the same order they were passed in

Returns the data for each provided type for the corresponding entity.

:::

add()

function World:add(
    entity: Entity, -- The entity
    id: Entity<T> -- The component ID to add
): ()

Adds a component ID to the entity.

This operation adds a single (component) id to an entity.

::: info This function is idempotent, meaning if the entity already has the id, this operation will have no side effects. :::

set()

function World:set(
    entity: Entity, -- The entity
    id: Entity<T>, -- The component ID to set
    data: T -- The data of the component's type
): ()

Adds or changes the entity's component.

query()

function World:query(
    ...: Entity -- The IDs to query with
): Query -- Returns the Query

Creates a query with the given IDs. Entities that satisfies the conditions of the query will be returned and their corresponding data.

Example: ::: code-group

for id, position, velocity in world:query(Position, Velocity) do
	-- Do something
end
for (const [id, position, velocity] of world.query(Position, Velocity) {
    // Do something
}

:::

:::info Queries are uncached by default, this is generally very cheap unless you have high fragmentation from e.g. relationships. :::