效果

警告

这些文档是为 SpongeAPI 7 编写的,可能已经过时。 如果你觉得你可以帮助更新它们,请提交一个 PR!

通过对 Sponge 中的效果 API 的使用,我们可以在服务端创建特殊的效果(Effect)。通过使用 Viewer 我们可以播放声音或者在服务端产生粒子效果。

播放聲音

对于任何给定的 Viewer ,我们都可以以非常简单的方式在指定位置播放声音:

import org.spongepowered.api.effect.Viewer;
import org.spongepowered.api.effect.sound.SoundTypes;

import com.flowpowered.math.vector.Vector3d;

viewer.playSound(SoundTypes.ENTITY_CREEPER_PRIMED, new Vector3d(1, 65, 1), 1);

现在让我们分析一下。首先,我们有一个定义了要播放的声音类型的 SoundType 对象。然后我们有一个 Vector3d 用于设定播放的位置。这一位置可以手动生成,也可以通过 LocationLocation#getPosition() 方法得到。在上面的示例中,声音将于 1, 65, 1 的位置播放。最后,我们有一个用于设置声音音量的数。这个音量是一个介于零和二之间的双精度浮点数。

现在我们可以播放基本的声音了,然后让我们接着更深入地调整声音。我们这里需要设置声音的音调为一个特定的值。因此,我们使用 PitchModulation 类以设置音量为一个特定的值。我们也可以使用 SoundCategory 以指定声音是什么类别的。下面是一段示例代码:

import org.spongepowered.api.effect.sound.PitchModulation;
import org.spongepowered.api.effect.sound.SoundCategories;

viewer.playSound(SoundTypes.ENTITY_CREEPER_PRIMED, SoundCategories.HOSTILE,
    new Vector3d(1, 65, 1), 1, PitchModulation.AFLAT0);

如果在播放声音时尚未指定 SoundCategory ,那么默认的将会是 SoundCategories#MASTER

生成粒子效果

和声音类似,我们可以通过 Viewer 类在世界上生成粒子效果:

import org.spongepowered.api.effect.particle.ParticleEffect;
import org.spongepowered.api.effect.particle.ParticleTypes;

ParticleEffect effect = ParticleEffect.builder()
        .type(ParticleTypes.LAVA)
        .quantity(50)
        .build();
viewer.spawnParticles(effect, position);

通过使用 ParticleEffect.Builder ,我们可以指定我们想要生成的粒子效果的类型,同时,我们还指定了五十种粒子效果。

现在,如果我们想要更精确地指定一种粒子,我们可以通过使用 ParticleTypes 类提供的各种粒子类型来完成这一点。比方说我们想生成正在被破坏的沙子方块的粒子效果,那么我们就需要用到 ParticleTypes#BLOCK_CRACK,同时我们还需要通过 ParticleOptions#BLOCK_STATE 指定我们想要使用沙子方块,也就是下面这个样子:

import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.effect.particle.ParticleOptions;

ParticleEffect particle = ParticleEffect.builder()
        .type(ParticleTypes.BLOCK_CRACK)
        .option(ParticleOptions.BLOCK_STATE, BlockTypes.SAND.getDefaultState())
        .build();
viewer.spawnParticles(particle, position);

药水效果

和声音及粒子效果一样,药水效果也需要用到 Builder,就像下面这样:

import org.spongepowered.api.effect.potion.PotionEffect;
import org.spongepowered.api.effect.potion.PotionEffectTypes;

PotionEffect potion = PotionEffect.builder()
        .potionType(PotionEffectTypes.HASTE)
        .duration(10)
        .amplifier(5)
        .build();

通过这样使用,我们生成了一个名为“急迫 V(Haste V)”的 PotionEffect ,并且其持续十个 Tick (译者注:0.5秒)。和声音及粒子不同,药水不能应用于一个 Viewer 。我们反而要去寻找一个支持 PotionEffectData 的实体,比如玩家。

import org.spongepowered.api.data.manipulator.mutable.PotionEffectData;
import org.spongepowered.api.entity.living.player.Player;

PotionEffectData effects = player.getOrCreate(PotionEffectData.class).get();
effects.addElement(potion);
player.offer(effects);

然后我们就从玩家手中获取到了一个 PotionEffectData ,我们将药水效果加入,并把该 PotionEffectData 设置回玩家。