FXGL17 - 游戏世界

252 阅读3分钟

PS:禁止拷贝形式转载,转载请以URL形式

PS:FXGL 准备写成一个系列,所以在该系列未完成前,该系列文章除了目录会被修改其他内容均可能被删改。

PS:本章内容为100%翻译自官方文档 Game World,该章节内容适用当前我整理的学习大纲分布故全盘翻译之

1. 简介

游戏世界负责添加、更新和删除实体。它还提供了通过各种标准查询实体的方法。游戏世界中的实体被认为是“活的”。一旦实体从世界中移除,它就不再可用并被清理。可以通过调用 getGameWorld() 来获取游戏应用程序的活动游戏世界的实例,或者如果您在“外部”,则可以使用 FXGL.getApp().getGameWorld()获取

Game World

The game world is responsible for adding, updating and removing entities. It also provides means of querying entities by various criteria. Entities that are in the game world are considered active (this can be checked: entity.isActive()). Once an entity is removed from the world, it is no longer usable and is cleaned up. The game world instance can be obtained by calling FXGL.getGameWorld().

2. 实体的添加和删除

PS:实体的具体创建可以参考 实体Entity 该章节内容

要将实体添加到游戏世界,使其成为游戏的一部分,只需调用:

GameWorld world = getGameWorld();
Entity e = ...
world.addEntity(e);

您可以通过类似的方式删除游戏世界中存在的实体:

world.removeEntity(e);

每个实体都知道它所依附的世界。所以,代替上面的,你可以调用一个更方便的版本:

e.removeFromWorld();

上面的两个调用在语义上是等价的。

3. 查询

以下片段允许您从世界请求特定实体。每个查询对实体组件都有一定的先决条件。例如,如果您基于 进行查询TypeComponent,则所有没有该组件的实体都将自动从搜索中过滤掉。一些查询返回实体列表,另一些则Optional<Entity>表示此类实体可能不存在。

3.1. 按类型

示例:我们有一个枚举EntityType,其中包含游戏中实体的有效类型。

List<Entity> enemies = world.getEntitiesByType(EntityType.ENEMY);

3.2. 按渲染层

示例:我们有几个渲染层,您希望所有对象都在背景层中。

List<Entity> backgroundEntities = world.getEntitiesByRenderLayer(RenderLayer.BACKGROUND);

3.3. 按 ID

示例:您可能允许实体的副本。这对于 RPG 类型的游戏特别有用,在这些游戏中有很多重复项。所以也许我们在游戏世界中放置了多个锻造,每个都有自己独特的IDComponent。虽然名称相同 - “Forge”,但其数字 ID 不同。

Optional<Entity> forge123 = world.getEntityByID("Forge", 123);

3.4. 按职位

示例:您想要网格中的特定对象。

Optional<Entity> entityAbove = world.getEntityAt(new Point2D(120, 80));

3.5. 按范围

例子:你想要的实体是一个特定的选择框。用于选择多个实体,查看爆炸物是否应该摧毁特定范围内的对象,或者查看玩家是否可以与对象交互。

List<Entity> entitiesNearby = world.getEntitiesInRange(new Rectangle2D(50, 50, 100, 100));

3.6. 按过滤器

示例:您有自己的实体规范,但不属于上述任何类别。

List<Entity> items = world.getEntitiesFiltered(e -> e instanceof ItemEntity);