org.bukkit.Location Java Examples

The following examples show how to use org.bukkit.Location. 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: SignsFeature.java    From AreaShop with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Constructor.
 * @param region The region to bind to
 */
public SignsFeature(GeneralRegion region) {
	setRegion(region);
	signs = new HashMap<>();
	// Setup current signs
	ConfigurationSection signSection = region.getConfig().getConfigurationSection("general.signs");
	if(signSection != null) {
		for(String signKey : signSection.getKeys(false)) {
			RegionSign sign = new RegionSign(this, signKey);
			Location location = sign.getLocation();
			if(location == null) {
				AreaShop.warn("Sign with key " + signKey + " of region " + region.getName() + " does not have a proper location");
				continue;
			}
			signs.put(sign.getStringLocation(), sign);
			signsByChunk.computeIfAbsent(sign.getStringChunk(), key -> new ArrayList<>())
					.add(sign);
		}
		allSigns.putAll(signs);
	}
}
 
Example #2
Source File: Renewable.java    From ProjectAres with GNU Affero General Public License v3.0 7 votes vote down vote up
boolean renew(BlockVector pos, MaterialData material) {
    // We need to do the entity check here rather than canRenew, because we are not
    // notified when entities move in our out of the way.
    if(!isClearOfEntities(pos)) return false;

    Location location = pos.toLocation(match.getWorld());
    Block block = location.getBlock();
    BlockState newState = location.getBlock().getState();
    newState.setMaterialData(material);

    BlockRenewEvent event = new BlockRenewEvent(block, newState, this);
    match.callEvent(event); // Our own handler will get this and remove the block from the pool
    if(event.isCancelled()) return false;

    newState.update(true, true);

    if(definition.particles) {
        NMSHacks.playBlockBreakEffect(match.getWorld(), pos, material.getItemType());
    }

    if(definition.sound) {
        NMSHacks.playBlockPlaceSound(match.getWorld(), pos, material.getItemType(), 1f);
    }

    return true;
}
 
Example #3
Source File: StructureService.java    From Crazy-Crates with MIT License 6 votes vote down vote up
/**
 * Swaps the edge corners if necessary, so the first edge will be at the lowest coordinates and the highest will be at the edge with the highest coordinates
 * @param startBlock - Any corner
 * @param endBlock - The other corner
 * @return Location[2] array - [0] = lowest edge, [1] = highest edge
 */
public static Location[] normalizeEdges(Location startBlock, Location endBlock) {
    int xMin, xMax, yMin, yMax, zMin, zMax;
    if (startBlock.getBlockX() <= endBlock.getBlockX()) {
        xMin = startBlock.getBlockX();
        xMax = endBlock.getBlockX();
    } else {
        xMin = endBlock.getBlockX();
        xMax = startBlock.getBlockX();
    }
    if (startBlock.getBlockY() <= endBlock.getBlockY()) {
        yMin = startBlock.getBlockY();
        yMax = endBlock.getBlockY();
    } else {
        yMin = endBlock.getBlockY();
        yMax = startBlock.getBlockY();
    }
    if (startBlock.getBlockZ() <= endBlock.getBlockZ()) {
        zMin = startBlock.getBlockZ();
        zMax = endBlock.getBlockZ();
    } else {
        zMin = endBlock.getBlockZ();
        zMax = startBlock.getBlockZ();
    }
    return new Location[] {new Location(startBlock.getWorld(), xMin, yMin, zMin), new Location(startBlock.getWorld(), xMax, yMax, zMax)};
}
 
Example #4
Source File: NBTEditor.java    From NBTEditor with MIT License 6 votes vote down vote up
private static Object getCompound( Block block ) {
	try {
		if ( block == null || !getNMSClass( "CraftBlockState" ).isInstance( block.getState() ) ) {
			return null;
		}
		Location location = block.getLocation();

		Object blockPosition = getConstructor( getNMSClass( "BlockPosition" ) ).newInstance( location.getBlockX(), location.getBlockY(), location.getBlockZ() );

		Object nmsWorld = getMethod( "getWorldHandle" ).invoke( location.getWorld() );

		Object tileEntity = getMethod( "getTileEntity" ).invoke( nmsWorld, blockPosition );

		Object tag = getNMSClass( "NBTTagCompound" ).newInstance();

		getMethod( "getTileTag" ).invoke( tileEntity, tag );

		return tag;
	} catch( Exception exception ) {
		exception.printStackTrace();
		return null;
	}
}
 
Example #5
Source File: SkriptYamlConstructor.java    From skript-yaml with MIT License 6 votes vote down vote up
@Override
public Object construct(Node node) {
	final Map<Object, Object> values = constructMapping((MappingNode) node);

	String w = (String) values.get("world");
	Double x = (Double) values.get("x");
	Double y = (Double) values.get("y");
	Double z = (Double) values.get("z");
	Double yaw = (Double) values.get("yaw");
	Double pitch = (Double) values.get("pitch");

	if (w == null | x == null || y == null || z == null || yaw == null || pitch == null)
		return null;

	return new Location(Bukkit.getServer().getWorld(w), x, y, z, (float) yaw.doubleValue(),
			(float) pitch.doubleValue());
}
 
Example #6
Source File: TeleportLogic.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Teleport the given {@link Player} to the given {@link Location}, loading the {@link org.bukkit.Chunk} before
 * teleporting and with the configured teleport delay if applicable.
 * @param player Player to teleport.
 * @param targetLocation Location to teleport the player to.
 * @param force True to override teleport delay, false otherwise.
 */
public void safeTeleport(@NotNull Player player, @NotNull Location targetLocation, boolean force) {
    Validate.notNull(player, "Player cannot be null");
    Validate.notNull(targetLocation, "TargetLocation cannot be null");

    log.log(Level.FINER, "safeTeleport " + player + " to " + targetLocation + (force ? " with force" : ""));
    final Location targetLoc = LocationUtil.centerOnBlock(targetLocation.clone());
    if (player.hasPermission("usb.mod.bypassteleport") || (teleportDelay == 0) || force) {
        PaperLib.teleportAsync(player, targetLoc);
    } else {
        player.sendMessage(tr("\u00a7aYou will be teleported in {0} seconds.", teleportDelay));
        BukkitTask tpTask = plugin.sync(() -> {
            pendingTeleports.remove(player.getUniqueId());
            PaperLib.teleportAsync(player, targetLoc);
        }, TimeUtil.secondsAsMillis(teleportDelay));
        pendingTeleports.put(player.getUniqueId(), new PendingTeleport(player.getLocation(), tpTask));
    }
}
 
Example #7
Source File: PacketPlayOutBlockChange.java    From NovaGuilds with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates the packet
 *
 * @param location location
 * @param material material
 * @param data     data byte (color, type etc.)
 * @throws IllegalAccessException    when something goes wrong
 * @throws InvocationTargetException when something goes wrong
 * @throws InstantiationException    when something goes wrong
 */
public PacketPlayOutBlockChange(Location location, Material material, int data) throws IllegalAccessException, InstantiationException, InvocationTargetException {
	packet = packetPlayOutBlockChangeClass.newInstance();

	xField.set(packet, location.getBlockX());
	yField.set(packet, location.getBlockY());
	zField.set(packet, location.getBlockZ());

	Object block;
	if(material == null) {
		block = getBlockAtMethod.invoke(
				Reflections.getHandle(location.getWorld()),
				location.getBlockX(),
				location.getBlockY(),
				location.getBlockZ()
		);
	}
	else {
		Object id = material.getId();
		block = getByIdMethod.invoke(null, id);
	}

	blockField.set(packet, block);
	dataField.set(packet, data);
}
 
Example #8
Source File: FishingBoat.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void build_trade_outpost(Location centerLoc) throws CivException {
	
	/* Add trade good to town. */
	TradeGood good = CivGlobal.getTradeGood(tradeGoodCoord);
	if (good == null) {
		throw new CivException("Couldn't find trade good at location:"+good);
	}
	
	if (!good.getInfo().water) {
		throw new CivException("Fishing boats can only be built on water goods.");
	}
	
	if (good.getTown() != null) {
		throw new CivException("Good is already claimed.");
	}
	
	good.setStruct(this);
	good.setTown(this.getTown());
	good.setCiv(this.getTown().getCiv());
	/* Save the good *afterwards* so the structure id is properly set. */
	this.setGood(good);
}
 
Example #9
Source File: DynamicLocation.java    From EffectLib with MIT License 6 votes vote down vote up
public DynamicLocation(Location location, Entity entity) {
    if (location != null) {
        this.location = location.clone();
    } else if (entity != null) {
        this.location = getEntityLocation(entity);
    } else {
        this.location = null;
    }
    if (entity != null) {
        this.entity = new WeakReference<Entity>(entity);
        this.entityOffset = this.location.toVector().subtract(getEntityLocation(entity).toVector());
    } else {
        this.entity = null;
    }
    this.originalLocation = this.location == null ? null : this.location.clone();
}
 
Example #10
Source File: PlayerBoundingBox.java    From CardinalPGM with MIT License 6 votes vote down vote up
public void sendSpawnPackets(Player viewer) {
    if (viewers.contains(viewer.getUniqueId())) return;
    Player player = Bukkit.getPlayer(this.player);
    Location loc = player.getLocation();
    int i = 0;
    for (int x = -1; x < 2; x += 2) {
        for (int z = -1; z < 2; z += 2) {
            Packet spawnPacket = new PacketPlayOutSpawnEntityLiving(
                    zombieID.get(i++), UUID.randomUUID(), 54,             // Entity id, UUID, and type (Zombie)
                    loc.getX() + (x * DamageIndicator.OFFSET), loc.getY(),// X, Y
                    loc.getZ() + (z * DamageIndicator.OFFSET),            // and Z coords
                    0, 0, 0,                                              // X, Y and Z Motion
                    (byte) 2, (byte) 0, (byte) 2,                         // Yaw, Pitch and Head Pitch
                    Watchers.toList(Watchers.INVISIBLE));                 // Metadata
            PacketUtils.sendPacket(viewer, spawnPacket);
        }
    }
    viewers.add(viewer.getUniqueId());
}
 
Example #11
Source File: v1_13_R2.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void sendWorldBorder(Player player, Color color, double size, Location centerLocation) {
    WorldBorder worldBorder = new WorldBorder();
    worldBorder.world = ((CraftWorld) centerLocation.getWorld()).getHandle();
    worldBorder.setCenter(centerLocation.getBlockX() + 0.5, centerLocation.getBlockZ() + 0.5);

    if (color == Color.Off) {
        worldBorder.setSize(Integer.MAX_VALUE);
    } else {
        worldBorder.setSize(size);
    }

    worldBorder.setWarningDistance(0);
    worldBorder.setWarningTime(0);

    if (color == Color.Red) {
        worldBorder.transitionSizeBetween(size, size - 1.0D, 20000000L);
    } else if (color == Color.Green) {
        worldBorder.transitionSizeBetween(size - 0.1D, size, 20000000L);
    }
    ((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutWorldBorder(worldBorder, PacketPlayOutWorldBorder.EnumWorldBorderAction.INITIALIZE));
}
 
Example #12
Source File: HologramEntityControllerImpl.java    From Holograms with MIT License 6 votes vote down vote up
@Override
public ItemHolder spawnItemHolder(HologramLine line, Location location, ItemStack itemstack) {
    WorldServer nmsWorld = ((CraftWorld) location.getWorld()).getHandle();
    EntityItemHolder item = new EntityItemHolder(nmsWorld, line);
    item.setPosition(location.getX(), location.getY() + line.getHeight(), location.getZ());
    item.setItem(itemstack);
    if (!addEntityToWorld(nmsWorld, item)) {
        plugin.getLogger().log(Level.WARNING, "Failed to spawn item entity in world " + location.getWorld().getName()
                + " at x:" + location.getX() + " y:" + location.getY() + " z:" + location.getZ());
    }
    EntityNameable armorStand = spawnNameable(line, location, false);
    item.setMount(armorStand);
    item.setLockTick(true);
    armorStand.setLockTick(true);
    return item;
}
 
Example #13
Source File: BedEffect.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void regionCreatedHandler(Region region) {
    if (!region.getEffects().containsKey(KEY)) {
        return;
    }
    if (region.getRawPeople().isEmpty() || region.getOwners().isEmpty()) {
        return;
    }
    UUID uuid = region.getOwners().iterator().next();
    Player player = Bukkit.getPlayer(uuid);
    if (player == null) {
        return;
    }
    player.setBedSpawnLocation(new Location(region.getLocation().getWorld(),
            region.getLocation().getX(), region.getLocation().getY() + 1, region.getLocation().getZ()));
}
 
Example #14
Source File: StructureService.java    From Crazy-Crates with MIT License 5 votes vote down vote up
/**
 * A comfort method for all lazy guys. Automatically switches to structure arrays, when the source is a folder, no file
 * @param source - The structure array folder or the structure NBT file
 * @param startEdge - The starting corner for pasting (lowest x, y, z coordinates)
 * @param rotation - You may rotate the structure by 90 degrees steps
 */
public static void loadAndInsertAny(File source, Location startEdge, Rotation rotation) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (source.isDirectory()) {
        DefinedStructure[] structures = StructureService.loadLegacyStructuresArray(source, startEdge.getWorld());
        StructureService.insertStructuresArray(structures, StructureService.loadAreaDimFile(source), startEdge, rotation.getNMSRot());
    } else {
        DefinedStructure structure = StructureService.loadLegacySingleStructure(source, startEdge.getWorld());
        StructureService.insertSingleStructure(structure, startEdge, rotation.getNMSRot());
    }
}
 
Example #15
Source File: ChestTerminalNetwork.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
private void collectExportRequests() {
    for (Location bus : exports) {
        BlockMenu menu = BlockStorage.getInventory(bus);

        if (menu.getItemInSlot(17) != null) {
            Optional<Block> target = getAttachedBlock(bus.getBlock());

            if (target.isPresent()) {
                menu.replaceExistingItem(17, CargoUtils.insert(bus.getBlock(), target.get(), menu.getItemInSlot(17)));
            }
        }

        if (menu.getItemInSlot(17) == null) {
            List<ItemStack> items = new ArrayList<>();

            for (int slot : slots) {
                ItemStack template = menu.getItemInSlot(slot);
                if (template != null) items.add(new CustomItem(template, 1));
            }

            if (!items.isEmpty()) {
                int index = Integer.parseInt(BlockStorage.getLocationInfo(bus, "index"));

                index++;
                if (index > (items.size() - 1)) {
                    index = 0;
                }

                BlockStorage.addBlockInfo(bus, "index", String.valueOf(index));
                itemRequests.add(new ItemRequest(bus, 17, items.get(index), ItemTransportFlow.WITHDRAW));
            }
        }
    }
}
 
Example #16
Source File: Effects.java    From TabooLib with MIT License 5 votes vote down vote up
public static void buildLine(Location locA, Location locB, Consumer<Location> action, double interval) {
    Vector vectorAB = locB.clone().subtract(locA).toVector();
    double vectorLength = vectorAB.length();
    vectorAB.normalize();
    for (double i = 0; i < vectorLength; i += interval) {
        action.accept(locA.clone().add(vectorAB.clone().multiply(i)));
    }
}
 
Example #17
Source File: FaweAdapter_1_12.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public org.bukkit.entity.Entity createEntity(Location location, BaseEntity state)
{
    Preconditions.checkNotNull(location);
    Preconditions.checkNotNull(state);

    CraftWorld craftWorld = (CraftWorld)location.getWorld();
    WorldServer worldServer = craftWorld.getHandle();

    Entity createdEntity = createEntityFromId(state.getTypeId(), craftWorld.getHandle());
    if (createdEntity != null)
    {
        CompoundTag nativeTag = state.getNbtData();
        if (nativeTag != null)
        {
            NBTTagCompound tag = (NBTTagCompound)fromNative(nativeTag);
            for (String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) {
                tag.remove(name);
            }
            readTagIntoEntity(tag, createdEntity);
        }
        createdEntity.setLocation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());

        worldServer.addEntity(createdEntity, CreatureSpawnEvent.SpawnReason.CUSTOM);
        return createdEntity.getBukkitEntity();
    }
    return null;
}
 
Example #18
Source File: ParticleEffect.java    From Crazy-Crates with MIT License 5 votes vote down vote up
/**
 * Sends the packet to all players in the list
 *
 * @param center Center location of the effect
 * @param players Receivers of the packet
 * @throws IllegalArgumentException If the player list is empty
 * @see #sendTo(Location center, Player player)
 */
public void sendTo(Location center, List<Player> players) throws IllegalArgumentException {
    if (players.isEmpty()) {
        throw new IllegalArgumentException("The player list is empty");
    }
    for (Player player : players) {
        sendTo(center, player);
    }
}
 
Example #19
Source File: CommonBlockEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
public void handleBlockBreak(Event event, Object source, BlockState blockState) {
    if (!GDFlags.BLOCK_BREAK) {
        return;
    }
    // Ignore air blocks
    if (blockState.getBlock().isEmpty()) {
        return;
    }

    // Special case
    if (source instanceof Block) {
        if (NMSUtil.getInstance().isBlockScaffolding(((Block) source))) {
            return;
        }
    }

    Player player = source instanceof Player ? (Player) source : null;
    final Location location = blockState.getLocation();
    if (location == null) {
        return;
    }

    final World world = blockState.getWorld();
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUID())) {
        return;
    }

    GDClaim targetClaim = this.storage.getClaimAt(location);

    final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, targetClaim, Flags.BLOCK_BREAK, source, blockState, player, TrustTypes.BUILDER, true);
    if (result == Tristate.FALSE) {
        ((Cancellable) event).setCancelled(true);
    }
}
 
Example #20
Source File: BlockInteractOcclusion.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void check(InteractWorldEvent e) {
    HawkPlayer pp = e.getHawkPlayer();
    Vector eyePos = pp.getPosition().clone().add(new Vector(0, pp.isSneaking() ? 1.54 : 1.62, 0));
    Vector direction = MathPlus.getDirection(pp.getYaw(), pp.getPitch());

    Location bLoc = e.getTargetedBlockLocation();
    Block b = bLoc.getBlock();
    WrappedBlock bNMS = WrappedBlock.getWrappedBlock(b, pp.getClientVersion());
    AABB targetAABB = new AABB(bNMS.getHitBox().getMin(), bNMS.getHitBox().getMax());

    double distance = targetAABB.distanceToPosition(eyePos);
    BlockIterator iter = new BlockIterator(pp.getWorld(), eyePos, direction, 0, (int) distance + 2);
    while (iter.hasNext()) {
        Block bukkitBlock = iter.next();

        if (bukkitBlock.getType() == Material.AIR || bukkitBlock.isLiquid())
            continue;
        if (bukkitBlock.getLocation().equals(bLoc))
            break;

        WrappedBlock iterBNMS = WrappedBlock.getWrappedBlock(bukkitBlock, pp.getClientVersion());
        AABB checkIntersection = new AABB(iterBNMS.getHitBox().getMin(), iterBNMS.getHitBox().getMax());
        Vector occludeIntersection = checkIntersection.intersectsRay(new Ray(eyePos, direction), 0, Float.MAX_VALUE);
        if (occludeIntersection != null) {
            if (occludeIntersection.distance(eyePos) < distance) {
                Placeholder ph = new Placeholder("type", iterBNMS.getBukkitBlock().getType());
                punishAndTryCancelAndBlockRespawn(pp, 1, e, ph);
                return;
            }
        }
    }
}
 
Example #21
Source File: MythicSpawnMobEvent.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    int a = amount.getInt(playerID);
    int l = level.getInt(playerID);
    Location location = loc.getLocation(playerID);
    for (int i = 0; i < a; i++) {
        try {
            new BukkitAPIHelper().spawnMythicMob(mob, location, l);
        } catch (InvalidMobTypeException e) {
            throw new QuestRuntimeException("MythicMob type " + mob + " is invalid.", e);
        }
    }
    return null;
}
 
Example #22
Source File: WorldGuardNoEntryHandler.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isSafeZone(Player player, Location location, TagType tagType) {
    switch(tagType) {
        case PLAYER: return !HookWorldGuard.allowsPVP(location);
        case MOB: return !HookWorldGuard.allowsMobCombat(location);

        default: return false;
    }
}
 
Example #23
Source File: SentinelWeaponHelper.java    From Sentinel with MIT License 5 votes vote down vote up
/**
 * Fires a snowball from the NPC at a target.
 */
public void fireSnowball(Location target) {
    sentinel.swingWeapon();
    sentinel.stats_snowballsThrown++;
    sentinel.faceLocation(target);
    Vector forward = getLivingEntity().getEyeLocation().getDirection();
    Location spawnAt = getLivingEntity().getEyeLocation().clone().add(forward.clone().multiply(sentinel.firingMinimumRange()));
    Entity ent = spawnAt.getWorld().spawnEntity(spawnAt, EntityType.SNOWBALL);
    ((Projectile) ent).setShooter(getLivingEntity());
    ent.setVelocity(sentinel.fixForAcc(target.clone().subtract(spawnAt).toVector().normalize().multiply(2.0))); // TODO: Fiddle with '2.0'.
}
 
Example #24
Source File: NMSUtilsHologramInteraction.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Hologram getHologramByLocation(List<Hologram> holograms, Location holoLocation) {
    for (Hologram holo : holograms) {
        if (holo.getLocation().getX() == holoLocation.getX() && holo.getLocation().getY() == holoLocation.getY()
                && holo.getLocation().getZ() == holoLocation.getZ()) {
            return holo;
        }
    }

    return null;
}
 
Example #25
Source File: Composter.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
private void pushItem(Block b, ItemStack output) {
    Optional<Inventory> outputChest = findOutputChest(b, output);

    if (outputChest.isPresent()) {
        outputChest.get().addItem(output);
    }
    else {
        Location loc = b.getRelative(BlockFace.UP).getLocation();
        b.getWorld().dropItemNaturally(loc, output);
    }
}
 
Example #26
Source File: WorldGuardHook.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
public static boolean isInIgnoredRegion(Location location) {
    if (!isInRegion(location)) {
        return false;
    }

    PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();

    return getRegionSet(location).getRegions()
        .stream()
        .anyMatch(region -> config.assistsRegionsIgnored.contains(region.getId()));
}
 
Example #27
Source File: uSkyBlock.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
public Location getSafeHomeLocation(final PlayerInfo p) {
    Location home = LocationUtil.findNearestSafeLocation(p.getHomeLocation(), null);
    if (home == null) {
        home = LocationUtil.findNearestSafeLocation(p.getIslandLocation(), null);
    }
    return home;
}
 
Example #28
Source File: Signs.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public boolean removeSign(Location sign)
{
	boolean b = signs.remove(MapKey.getKey(sign)) == null ? false : true;
	if(b)
		sign.getWorld().getBlockAt(sign).setType(Material.AIR);
	return b;
}
 
Example #29
Source File: NMS_v1_9_R1.java    From Crazy-Crates with MIT License 5 votes vote down vote up
@Override
public void pasteSchematic(File f, Location loc) {
    loc = loc.subtract(2, 1, 2);
    try {
        FileInputStream fis = new FileInputStream(f);
        NBTTagCompound nbt = NBTCompressedStreamTools.a(fis);
        short width = nbt.getShort("Width");
        short height = nbt.getShort("Height");
        short length = nbt.getShort("Length");
        byte[] blocks = nbt.getByteArray("Blocks");
        byte[] data = nbt.getByteArray("Data");
        fis.close();
        //paste
        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                for (int z = 0; z < length; ++z) {
                    int index = y * width * length + z * width + x;
                    final Location l = new Location(loc.getWorld(), x + loc.getX(), y + loc.getY(), z + loc.getZ());
                    int b = blocks[index] & 0xFF;//make the block unsigned, so that blocks with an id over 127, like quartz and emerald, can be pasted
                    final Block block = l.getBlock();
                    block.setType(Material.getMaterial(b));
                    block.setData(data[index]);
                    //you can check what type the block is here, like if(m.equals(Material.BEACON)) to check if it's a beacon
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #30
Source File: EntityTools.java    From StackMob-3 with GNU General Public License v3.0 5 votes vote down vote up
private Location getSpawnLocation(Entity original){
    Location dupeLoc = original.getLocation();
    if (original instanceof Zombie || original instanceof Skeleton) {
        // Make location in the middle of the block, prevents wall glitching due to "safe spawn errors"
        dupeLoc.setX(dupeLoc.getBlockX() + 0.5);
        dupeLoc.setZ(dupeLoc.getBlockZ() + 0.5);
    }
    return dupeLoc;
}