Spawnen eines Entitys

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.

Zum Beispiel könnten wir versuchen einen Creeper zu spawnen:

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.

Bemerkung

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.

Sobald wir eine Entity erstellt haben, können wir die Welt benutzen um die Entity zu spawnen. Für das Spawnen sollten wir zudem einen Grund (Cause) angeben, sodass andere Plugins entsprechend reagieren können. Zum Spawnen von `` Entity``s ist es am Besten, wenn einen SpawnType als Teil des Kontextes angeben. In diesem Beispiel geben wir an, dass unsere Entity durch ein Plugin gespawnt wurde, aber wir können hier jeglichen Grund angeben, der am Besten beschreibt, warum wir diese spawnen, beispielsweise ein Monsterspawner (Siehe SpawnTypes#MOB_SPAWNER), oder ein Spawnei (Siehe SpawnTypes#SPAWN_EGG).