Invoquer une Entité

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.

Par exemple, essayons d’invoquer un Creeper :

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.

Note

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.

Une fois que nous avons créé notre Entity, nous pouvons utiliser le monde pour faire apparaître cette Entity. Nous aurons besoin de spécifier une Cause pour l’apparition, pour que les autres plugins puissent la gérer en conséquence. Pour faire apparaître des Entitys, il est préférable d’utiliser un SpawnType dans le contexte. Dans cet exemple, nous avons déclaré que c’est un plugin qui a fait apparaître l’entité, mais nous pouvons mettre n’importe quel autre cause/contexte qui décrirait au mieux pourquoi on la fait apparaître, par exemple avec un mob spawner (Voir SpawnTypes#MOB_SPAWNER), ou un oeuf de créature (Voir SpawnTypes#SPAWN_EGG).