org.bukkit.entity.Entity Java Examples

The following examples show how to use org.bukkit.entity.Entity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetherPortals.java    From askyblock with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #2
Source File: ExprAttacked.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: Molotov.java    From ce with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #4
Source File: LivingEntityShopListener.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
@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);
				}
			}
		}
	}
}
 
Example #5
Source File: SpawnEntityCustomNbtInjectorTest.java    From Item-NBT-API with MIT License 6 votes vote down vote up
@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);
		}
	}
}
 
Example #6
Source File: EntityRemoveListener.java    From StackMob-3 with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #7
Source File: PlayerHider.java    From AACAdditionPro with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #8
Source File: SentinelEventHandler.java    From Sentinel with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: SentinelEventHandler.java    From Sentinel with MIT License 6 votes vote down vote up
@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);
            }
        }
    }
}
 
Example #10
Source File: Vectors.java    From TabooLib with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #11
Source File: CooldownEffect.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: SimpleHoloManager.java    From HoloAPI with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: Compat19.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #14
Source File: EntityExplodeListener.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
@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);
    }
}
 
Example #15
Source File: PetEntityListener.java    From SonarPet with GNU General Public License v3.0 5 votes vote down vote up
@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());
    }
}
 
Example #16
Source File: ManaEffect.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
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";
    }
}
 
Example #17
Source File: SpellComponent.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: SpigotWrapper.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@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);
    }
}
 
Example #19
Source File: ProjectileMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
  }
}
 
Example #20
Source File: GiveCommand.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: FallEffect.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: PlayerBoundingBox.java    From QualityArmory with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: I18n11601.java    From TabooLib with MIT License 5 votes vote down vote up
@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();
}
 
Example #24
Source File: EscapePlan.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onAttack(EntityDamageByEntityEvent event, PlayerDetails details) {
	Entity entity = event.getEntity();
	if (entity instanceof LivingEntity) {
		details.consumeItem();
		fire(entity.getLocation(), details, entity);
	}
}
 
Example #25
Source File: EntityExplodeEvent.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #26
Source File: BukkitCommandSource.java    From BlueMap with MIT License 5 votes vote down vote up
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;
}
 
Example #27
Source File: EntityTypeFilter.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
public EntityTypeFilter(Class<? extends Entity> type) {
  this.type = type;
}
 
Example #28
Source File: EventResolver.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
default DamageInfo resolveDamage(EntityDamageEvent.DamageCause damageType, Entity victim) {
    return resolveDamage(damageType, victim, (PhysicalInfo) null);
}
 
Example #29
Source File: StackTools.java    From StackMob-3 with GNU General Public License v3.0 4 votes vote down vote up
public static boolean hasSizeMoreThanOne(Entity entity){
    return hasValidData(entity) &&
            getSize(entity) > 1;
}
 
Example #30
Source File: EntityUtilTest.java    From uSkyBlock with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testGetEntity() {
    List<Entity> testList = new ArrayList<>();

    ArmorStand fakeArmorStand = mock(ArmorStand.class);
    Cow fakeCow = mock(Cow.class);
    Evoker fakeEvoker = mock(Evoker.class);
    Guardian fakeGuardian = mock(Guardian.class);
    Pig fakePig = mock(Pig.class);
    PigZombie fakePigZombie = mock(PigZombie.class);
    Pillager fakePillager = mock(Pillager.class);
    Sheep fakeSheep = mock(Sheep.class);
    Skeleton fakeSkeleton = mock(Skeleton.class);
    Turtle fakeTurtle = mock(Turtle.class);
    Villager fakeVillager = mock(Villager.class);
    WanderingTrader fakeWanderingTrader = mock(WanderingTrader.class);

    testList.add(fakeArmorStand);
    testList.add(fakeCow);
    testList.add(fakeEvoker);
    testList.add(fakeGuardian);
    testList.add(fakePig);
    testList.add(fakePigZombie);
    testList.add(fakePillager);
    testList.add(fakeSheep);
    testList.add(fakeSkeleton);
    testList.add(fakeTurtle);
    testList.add(fakeVillager);
    testList.add(fakeWanderingTrader);

    List<Sheep> sheepList = EntityUtil.getEntity(testList, Sheep.class);
    assertEquals(1, sheepList.size());
    assertEquals(fakeSheep, sheepList.get(0));

    List<Animals> animalsList = EntityUtil.getAnimals(testList);
    assertEquals(4, animalsList.size());
    assertTrue(animalsList.contains(fakeCow));
    assertTrue(animalsList.contains(fakePig));
    assertTrue(animalsList.contains(fakeSheep));
    assertTrue(animalsList.contains(fakeTurtle));

    List<Monster> monsterList = EntityUtil.getMonsters(testList);
    assertEquals(5, monsterList.size());
    assertTrue(monsterList.contains(fakeEvoker));
    assertTrue(monsterList.contains(fakeGuardian));
    assertTrue(monsterList.contains(fakePigZombie));
    assertTrue(monsterList.contains(fakePillager));
    assertTrue(monsterList.contains(fakeSkeleton));

    List<NPC> npcList = EntityUtil.getNPCs(testList);
    assertEquals(2, npcList.size());
    assertTrue(npcList.contains(fakeVillager));
    assertTrue(npcList.contains(fakeWanderingTrader));
}