生成實體
You will need three things for spawning an Entity: a Position as a Vector3d, a ServerWorld, and an
EntityType. The process for getting these is quite simple, you just need to grab a Position from
somewhere in your plugin code and choose the type of Entity you wish to spawn.
例如,讓我們試著生成一隻苦力怕:
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.monster.Creeper;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.event.EventContextKeys;
import org.spongepowered.api.event.cause.entity.SpawnTypes;
import org.spongepowered.api.world.server.ServerLocation;
import org.spongepowered.api.world.server.ServerWorld;
public void spawnEntity(ServerLocation spawnLocation) {
ServerWorld world = spawnLocation.world();
Creeper creeper = world.createEntity(EntityTypes.CREEPER, spawnLocation.position());
// 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.server().causeStackManager().pushCauseFrame()) {
frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PLUGIN);
world.spawnEntity(creeper);
}
}
This will grab the world from our ServerLocation, which we will need for the actual spawning. Next, it uses
EntityVolume.Modifiable#createEntity(Supplier, Vector3d) to create the entity, but do note that this does not
spawn the entity into the world, it just will create it. We will need to specify the type of Entity to spawn, and
the co-ordinates from our Location.
備註
EntityTypes.CREEPER is not an EntityType itself, but a DefaultedRegistryReference to one. As a
registry reference is also a Supplier, it can be passed to createEntity directly. If you already have an
EntityType, use EntityVolume.Modifiable#createEntity(EntityType, Vector3d) instead. See
Migrating from API 7 to API 8 for more on registry references.
一旦我們建立了我們的 Entity,我們就可以使用世界來生成該 Entity。我們應該指定一個生成的 Cause 以確保其他插件能夠正確處理。對於生成 Entity,最好的方式是使用一個 SpawnType 作為情境的一部份。在這個範例中,我們我們聲明我們的實體是從插件中生成的,然而我們可以指定任何事件原因/情境來以最好的方式描述為何我們要生成這個實體,例如生怪磚(參閱SpawnTypes#MOB_SPAWNER),或刷怪蛋(參閱SpawnTypes#SPAWN_EGG)。