下面列出了怎么用org.bukkit.Location的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
}
@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;
}
@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));
}
@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());
}
/**
* 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));
}
}
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();
}
/**
* 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)};
}
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;
}
/**
* 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);
}
@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);
}
@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()));
}
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;
}
}
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());
}
public static Location getOtherEdge(File source, Location startEdge) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {
DefinedStructure structure = StructureService.loadLegacySingleStructure(source, startEdge.getWorld());
NBTTagCompound fileTag = new NBTTagCompound();
fileTag = structure.a(fileTag);
NBTTagList list = (NBTTagList) fileTag.get("size");
return startEdge.clone().add(Integer.parseInt(list.get(0).toString()) - 1, Integer.parseInt(list.get(1).toString()) - 1, Integer.parseInt(list.get(2).toString()) - 1);
}
@SuppressWarnings("null")
@Override
public Collection<? extends Region> getRegionsAt_i(final Location l) {
final List<ResidenceRegion> ress = new ArrayList<>();
final ClaimedResidence res = Residence.getInstance().getResidenceManager().getByLoc(l);
if (res == null)
return Collections.emptyList();
ress.add(new ResidenceRegion(l.getWorld(), res));
return ress;
}
/**
* 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());
}
}
@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;
}
public DeathmatchArena(Location loc){
this.loc = loc;
built = false;
teleportSpots = new ArrayList<>();
enable = true;
teleportSpots.add(loc);
checkIfSchematicCanBePasted();
}
@Override
public void playEffect(final Location location, final Effect effect, final int data, final int radius) {
TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override
public void run(Object value) {
parent.playEffect(location, effect, data, radius);
}
});
}
@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;
}
/**
* 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'.
}
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);
}
}
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;
}
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;
}
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);
}
}
@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();
}
}
public Location getSafeHomeLocation(final PlayerInfo p) {
Location home = LocationUtil.findNearestSafeLocation(p.getHomeLocation(), null);
if (home == null) {
home = LocationUtil.findNearestSafeLocation(p.getIslandLocation(), null);
}
return home;
}
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()));
}
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;
}
@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;
}
}