-
-
Notifications
You must be signed in to change notification settings - Fork 559
Game World
Game world is responsible for registering, updating and removing entities. It also provides means of querying entities by various criteria. Entities that are registered in the game world are considered "live". Once an entity is removed from the world, it is no longer usable and is cleaned up. An instance of the active game world for a game application can be obtained by calling getGameWorld()
, or if you are "outside", then FXGL.getApp().getGameWorld()
.
To register an entity means to add it to the game world, so it becomes part of the "live" game. To do so, simply call:
GameWorld world = getGameWorld();
Entity e = ...
world.addEntity(e);
The entity will become active and part of the game. You can remove the entity that exists in the game world in a similar way:
world.removeEntity(e);
Each entity knows about the world it is attached to. So, instead of the above, you can call a more convenient version:
e.removeFromWorld();
The two calls above are semantically equivalent. In fact, if you check out the source the latter simply delegates the call to the former.
The following snippets allow you to request specific entities from the world. It's worth noting that each query has certain preconditions on the entity components. For example, if you do a query based on TypeComponent
, then all entities that don't have that component will be automatically filtered out from the search. Some queries return a list of entities, others Optional<Entity>
signifying that such entity may not exist.
Example: we have an enum EntityType
that contains valid types for entities in your game.
List<Entity> enemies = world.getEntitiesByType(EntityType.ENEMY);
Example: we have several render layers and you want all objects in the background layer.
List<Entity> backgroundEntities = world.getEntitiesByRenderLayer(RenderLayer.BACKGROUND);
Example: you might allow copies of entities. This is especially useful for RPG type games, where you have lots of duplicates. So maybe we placed multiple forges in the game world, each will have its own unique IDComponent
. While the name is the same - "Forge", its numeric id is different.
Optional<Entity> forge123 = world.getEntityByID("Forge", 123);
Example: you want a particular object in the grid.
Optional<Entity> entityAbove = world.getEntityAt(new Point2D(120, 80));
Example: you want entities is a particular selection box. Useful to select multiple entities, to see if an explosive should destroy objects in a certain range, or to see if the player can interact with an object.
List<Entity> entitiesNearby = world.getEntitiesInRange(new Rectangle2D(50, 50, 100, 100));
Example: you have your own specifications of entities that you want that do not fall into any of the categories above.
List<Entity> items = world.getEntitiesFiltered(e -> e instanceof ItemEntity);