生成一个实体

警告

这些文档是为 SpongeAPI 7 编写的,可能已经过时。 如果你觉得你可以帮助更新它们,请提交一个 PR!

你需要四样数据以指定如何在世界上生成实体:EntityLocationExtentEntityType。获取这些东西其实相当简单,你需要关心的只有需要插件代码中指定的 Location 和你想要生成的 Entity 的类型。

例如,让我们试着去生成一个爬行者:

import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;

import java.util.Optional;

public void spawnEntity(Location<World> spawnLocation) {
    World world = spawnLocation.getExtent();

    Entity creeper = world.createEntity(EntityTypes.CREEPER, spawnLocation.getPosition());

    // We need to push a new cause StackFrame to the stack so we can add our own causes
    // In previous versions of the API you had to submit a Cause parameter
    // that would often not contain the real root cause
    // By default the current plugin's PluginContainer is already pushed to the stack.
    try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PLUGIN);
        world.spawnEntity(creeper);
    }
}

这样我们就指定了 Location 对应的世界,用于生成我们想要生成的实体。然后,我们通过 EntityUniverse#createEntity(EntityType, Vector3d) 方法创建了一个实体,不过需要注意的是它只是创建了一个实体,还没有在世界上生成它。我们需要指定 Entity 的类型,和其具体的 Location

一量我们创建了我们的 Entity 我们就可以通过世界生成实体于其上了。我们需要指定一个用于生成的 Cause 以保证其他插件能正确处理。对于生成实体而言,最好的方式是使用 SpawnType 作为根事件上下文。在这个示例中,我们注意到我们的实体是插件生成的,不过,我们也可以指定一些事件原因或上下文用于描述我们为何要生成这个实体,比如由于一个刷怪笼(参见 SpawnTypes#MOB_SPAWNER)或者一个刷怪蛋(参见 SpawnTypes#SPAWN_EGG)。