Spawnowanie Entity (Moba)

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.

Na przykład, spróbujmy zespawnować Creeper’a:

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.

Informacja

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 Migracja z API 7 do API 8 for more on registry references.

Kiedy już utworzyliśmy nasze Entity możemy użyć obiektu świata do zespawnowania go. Przed tym powinniśmy określić Cause dla spawnu, czyli powodu, tak aby inne pluginy mogły go odpowiednio obsłużyć. Do tworzenia Entitys, najlepiej użyć SpawnType jako części kontekstu. W tym przykładzie oznajmiamy że nasze Entity zostało zespawnowane przez plugin. Oczywiście możemy również sprawić, że będzie to każda jakakolwiek inna przyczyna/kontekst, który najlepiej opisuje, dlaczego Entity się pojawiło, np. spawner potworów (zobacz SpawnTypes#MOB_SPAWNER) lub spawn egg (zobacz SpawnTypes#SPAWN_EGG).