下面列出了怎么用org.bukkit.entity.Entity的API类实例代码及写法,或者点击链接到github查看源代码。
public static void entityPush(Entity entity, Location to, double velocity) {
Location from = entity.getLocation();
Vector test = to.clone().subtract(from).toVector();
double elevation = test.getY();
Double launchAngle = calculateLaunchAngle(from, to, velocity, elevation, 20.0D);
double distance = Math.sqrt(Math.pow(test.getX(), 2.0D) + Math.pow(test.getZ(), 2.0D));
if (distance != 0.0D) {
if (launchAngle == null) {
launchAngle = Math.atan((40.0D * elevation + Math.pow(velocity, 2.0D)) / (40.0D * elevation + 2.0D * Math.pow(velocity, 2.0D)));
}
double hangTime = calculateHangTime(launchAngle, velocity, elevation, 20.0D);
test.setY(Math.tan(launchAngle) * distance);
test = normalizeVector(test);
Vector noise = Vector.getRandom();
noise = noise.multiply(0.1D);
test.add(noise);
velocity = velocity + 1.188D * Math.pow(hangTime, 2.0D) + (Numbers.getRandom().nextDouble() - 0.8D) / 2.0D;
test = test.multiply(velocity / 20.0D);
entity.setVelocity(test);
}
}
/**
* Called when a projectile hits a block, to auto-remove Sentinel-fired arrows quickly.
*/
@EventHandler
public void onProjectileHitsBlock(ProjectileHitEvent event) {
if (SentinelPlugin.instance.arrowCleanupTime <= 0) {
return;
}
final Projectile projectile = event.getEntity();
ProjectileSource source = projectile.getShooter();
if (!(source instanceof Entity)) {
return;
}
SentinelTrait sentinel = SentinelUtilities.tryGetSentinel((Entity) source);
if (sentinel == null) {
return;
}
Bukkit.getScheduler().scheduleSyncDelayedTask(SentinelPlugin.instance, new Runnable() {
@Override
public void run() {
if (projectile.isValid()) {
projectile.remove();
}
}
}, SentinelPlugin.instance.arrowCleanupTime);
}
@Override
public void modifyInformation(final Player observer, final Entity entity)
{
validate(observer, entity);
if (setModifyInformation(observer, entity.getEntityId(), false)) {
//Create new packet which destroys the entity
final PacketContainer destroyEntity = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
destroyEntity.getIntegerArrays().write(0, new int[]{entity.getEntityId()});
// Make the entity disappear
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, destroyEntity);
} catch (final InvocationTargetException e) {
throw new RuntimeException("Cannot send server packet.", e);
}
}
}
@SuppressWarnings("deprecation")
@Override
public void effect(Event e, ItemStack item, final int level) {
if(e instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) e;
Entity target = event.getEntity();
World world = target.getWorld();
world.playEffect(target.getLocation(), Effect.POTION_BREAK, 10);
double boundaries = 0.1*level;
for(double x = boundaries; x >= -boundaries; x-=0.1)
for(double z = boundaries; z >= -boundaries; z-=0.1) {
FallingBlock b = world.spawnFallingBlock(target.getLocation(), Material.FIRE.getId(), (byte) 0x0);
b.setVelocity(new Vector(x, 0.1, z));
b.setDropItem(false);
}
}
}
@Override
public void test() throws Exception {
if (!NBTInjector.isInjected())
return;
if (!Bukkit.getWorlds().isEmpty()) {
World world = Bukkit.getWorlds().get(0);
try {
Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), EntityType.ARMOR_STAND);
entity = NBTInjector.patchEntity(entity);
NBTCompound comp = NBTInjector.getNbtData(entity);
comp.setString("Hello", "World");
NBTEntity nbtent = new NBTEntity(entity);
if (!nbtent.toString().contains("__extraData:{Hello:\"World\"}")) {
throw new NbtApiException("Custom Data did not save to the Entity!");
}
comp.removeKey("Hello");
entity.remove();
} catch (Exception ex) {
throw new NbtApiException("Wasn't able to use NBTEntities!", ex);
}
}
}
@Override
public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, final Vector velocity, String... lines) {
int simpleId = TagIdGenerator.next(lines.length);
final Hologram hologram = new HologramFactory(HoloAPI.getCore()).withFirstTagId(simpleId).withSaveId(simpleId + "").withText(lines).withLocation(location).withSimplicity(true).build();
for (Entity e : hologram.getDefaultLocation().getWorld().getEntities()) {
if (e instanceof Player) {
hologram.show((Player) e, true);
}
}
BukkitTask t = HoloAPI.getCore().getServer().getScheduler().runTaskTimer(HoloAPI.getCore(), new Runnable() {
@Override
public void run() {
Location l = hologram.getDefaultLocation();
l.add(velocity);
hologram.move(l.toVector());
}
}, 1L, 1L);
new HologramRemoveTask(hologram, t).runTaskLater(HoloAPI.getCore(), secondsUntilRemoved * 20);
return hologram;
}
@EventHandler
public void onBlockIgnites(BlockIgniteEvent event) {
if (event.isCancelled()) {
return;
}
if (!SentinelPlugin.instance.preventExplosionBlockDamage) {
return;
}
if (event.getIgnitingEntity() instanceof Projectile) {
ProjectileSource source = ((Projectile) event.getIgnitingEntity()).getShooter();
if (source instanceof Entity) {
SentinelTrait sourceSentinel = SentinelUtilities.tryGetSentinel((Entity) source);
if (sourceSentinel != null) {
event.setCancelled(true);
}
}
}
}
@EventHandler(ignoreCancelled = true)
void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
// block damaging of shopkeepers
if (plugin.isShopkeeper(entity)) {
event.setCancelled(true);
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent) event;
if (evt.getDamager() instanceof Monster) {
Monster monster = (Monster) evt.getDamager();
// reset target, future targeting should get prevented somewhere else:
if (entity.equals(monster.getTarget())) {
monster.setTarget(null);
}
}
}
}
}
@Override
public boolean init(final Expression<?>[] vars, final int matchedPattern, final Kleenean isDelayed, final ParseResult parser) {
if (!ScriptLoader.isCurrentEvent(EntityDamageEvent.class, EntityDeathEvent.class, VehicleDamageEvent.class, VehicleDestroyEvent.class)) {
Skript.error("The expression 'victim' can only be used in a damage or death event", ErrorQuality.SEMANTIC_ERROR);
return false;
}
final String type = parser.regexes.size() == 0 ? null : parser.regexes.get(0).group();
if (type == null) {
this.type = EntityData.fromClass(Entity.class);
} else {
final EntityData<?> t = EntityData.parse(type);
if (t == null) {
Skript.error("'" + type + "' is not an entity type", ErrorQuality.NOT_AN_EXPRESSION);
return false;
}
this.type = t;
}
return true;
}
private void cleanupEntity(Entity entity) {
// Check if entity is a mob, since they despawn on chunk unload.
if (entity instanceof Monster) {
sm.getCache().remove(entity.getUniqueId());
StackTools.removeSize(entity);
return;
}
// Add to storage
if (StackTools.hasValidData(entity)) {
int stackSize = StackTools.getSize(entity);
StackTools.removeSize(entity);
if (stackSize <= 1 && stackSize != GlobalValues.NO_STACKING) {
return;
}
if (sm.getCustomConfig().getBoolean("remove-chunk-unload")) {
entity.remove();
return;
}
sm.getCache().put(entity.getUniqueId(), stackSize);
}
}
public CooldownEffect(Spell spell, String key, Object target, Entity origin, int level, ConfigurationSection section) {
super(spell, key, target, origin, level, section);
String configDamage = section.getString("cooldown", "5000");
this.silent = section.getBoolean("silent", false);
this.cooldown = (int) Math.round(Spell.getLevelAdjustedValue(configDamage, level, target, spell));
String tempTarget = section.getString("target", "not-a-string");
String abilityName = section.getString("ability", "not-a-string");
if (!tempTarget.equals("not-a-string")) {
this.target = tempTarget;
} else {
this.target = "self";
}
if (!abilityName.equals("not-a-string")) {
this.abilityName = abilityName;
} else {
this.abilityName = "self";
}
this.config = section;
}
@EventHandler(ignoreCancelled = true)
public void onShootBow(EntityShootBowEvent e) {
if (!(e.getEntity() instanceof Player)) {
return;
}
Player p = (Player) e.getEntity();
Entity proj = e.getProjectile();
List<String> Pots = RedProtect.get().config.globalFlagsRoot().worlds.get(p.getWorld().getName()).deny_potions;
if ((proj instanceof TippedArrow)) {
TippedArrow arr = (TippedArrow) proj;
if (Pots.contains(arr.getBasePotionData().getType().name())) {
RedProtect.get().lang.sendMessage(p, "playerlistener.denypotion");
e.setCancelled(true);
}
}
}
/**
* Prevent the Nether spawn from being blown up
*
* @param e - event
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onExplosion(final EntityExplodeEvent e) {
if (Settings.newNether) {
// Not used in the new nether
return;
}
// Find out what is exploding
Entity expl = e.getEntity();
if (expl == null) {
return;
}
// Check world
if (!e.getEntity().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_nether")
|| e.getEntity().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_the_end")) {
return;
}
Location spawn = e.getLocation().getWorld().getSpawnLocation();
Location loc = e.getLocation();
if (spawn.distance(loc) < Settings.netherSpawnRadius) {
e.blockList().clear();
}
}
public FallEffect(Spell spell, String key, Object target, Entity origin, int level, String value) {
super(spell, key, target, origin, level, value);
this.distance = Math.round(Spell.getLevelAdjustedValue(value, level, target, spell));
this.target = "self";
this.silent = false;
this.setFall = false;
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event) {
try {
final Entity entity = event.getEntity();
final Location location = entity.getLocation();
final IslandManager islandManager = IridiumSkyblock.getIslandManager();
if (!islandManager.isIslandWorld(location)) return;
if (!IridiumSkyblock.getConfiguration().allowExplosions)
event.setCancelled(true);
} catch (Exception ex) {
IridiumSkyblock.getInstance().sendErrorMessage(ex);
}
}
private Location getLocation() {
Location location = null;
if (delegate instanceof Entity) {
location = ((Entity) delegate).getLocation();
}
if (delegate instanceof BlockCommandSender) {
location = ((BlockCommandSender) delegate).getBlock().getLocation();
}
return location;
}
@Override
public String getName(Player player, Entity entity) {
JsonObject locale = cache.get(player == null ? "zh_cn" : player.getLocale());
if (locale == null) {
locale = cache.get("en_gb");
}
if (locale == null) {
return "[ERROR LOCALE]";
}
JsonElement element = locale.get(NMS.handle().getName(entity));
return element == null ? entity.getName() : element.getAsString();
}
public EntityExplodeEvent(final Entity what, final Location location, final List<Block> blocks, final float yield) {
super(what);
this.location = location;
this.blocks = blocks;
this.yield = yield;
this.cancel = false;
}
@Override
public void onAttack(EntityDamageByEntityEvent event, PlayerDetails details) {
Entity entity = event.getEntity();
if (entity instanceof LivingEntity) {
details.consumeItem();
fire(entity.getLocation(), details, entity);
}
}
@Override
public boolean intersects(Entity shooter, Location check, Entity base) {
boolean intersectsBodyWIDTH = BoundingBoxUtil.within2DWidth(base, check, bodyWidthRadius, bodyWidthRadius);
if (!intersectsBodyWIDTH)
return false;
return intersectsHead(check, base) || intersectsBody(check, base);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
Entity e = event.getEntity();
if (plugin.isPet(e)) {
IEntityPet entityPet = plugin.getPetEntity(e);
PetDamageEvent damageEvent = new PetDamageEvent(entityPet.getPet(), event.getCause(), event.getDamage());
EchoPet.getPlugin().getServer().getPluginManager().callEvent(damageEvent);
event.setDamage(damageEvent.getDamage());
event.setCancelled(damageEvent.isCancelled());
}
}
public SpellComponent(Spell spell,
String key,
Object target,
Entity origin,
int level) {
this.spell = spell;
this.key = key;
this.target = target;
this.origin = origin;
this.level = level;
}
@Override
public void teleportEntity(
@NotNull Entity entity,
@NotNull Location location,
@Nullable PlayerTeleportEvent.TeleportCause cause) {
if (cause == null) {
entity.teleport(location);
} else {
entity.teleport(location, cause);
}
}
@Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) {
List<String> result = new ArrayList<>();
switch (args.length) {
case 2:
for (Player player : Bukkit.getOnlinePlayers()) {
result.add(player.getName());
}
result.add("@a");
result.add("@r");
if (sender instanceof Entity || sender instanceof BlockState) {
result.add("@aw");
result.add("@p");
result.add("@rw");
}
break;
case 3:
for (ToolType type : ToolType.values()) {
for (Material mat : type.getToolMaterials()) {
result.add(mat.toString());
}
}
if (ConfigurationManager.getConfig("BuildersWand.yml").getBoolean("enabled")) {
for (ItemStack wand : BuildersWandListener.getWands()) {
result.add(wand.getItemMeta().getDisplayName().replaceAll(" ", "_"));
}
}
break;
}
return result;
}
public ManaEffect(Spell spell, String key, Object target, Entity origin, int level, ConfigurationSection section) {
super(spell, key, target, origin, level, section);
this.mana = (int) Math.round(Spell.getLevelAdjustedValue(section.getString("mana", "5"), level, target, spell));
this.silent = section.getBoolean("silent", false);
String tempTarget = section.getString("target", "not-a-string");
if (!tempTarget.equals("not-a-string")) {
this.target = tempTarget;
} else {
this.target = "self";
}
}
public static @Nullable ProjectileDefinition getProjectileDefinition(Entity entity) {
MetadataValue metadataValue = entity.getMetadata("projectileDefinition", PGM.get());
if (metadataValue != null) {
return (ProjectileDefinition) metadataValue.value();
} else if (launchingDefinition.get() != null) {
return launchingDefinition.get();
} else {
return null;
}
}
@Override
public void setTarget(Entity arg0, boolean arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean intersectsBody(Location check, Entity base) {
return false;
}
@Override
public boolean teleport(Entity destination, PlayerTeleportEvent.TeleportCause cause) {
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] exp, int arg1, Kleenean arg2, ParseResult arg3) {
entity = (Expression<Entity>) exp[0];
return true;
}