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