下面列出了org.bukkit.Location#distanceSquared ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onMove(PlayerMoveEvent e) {
final Info info = plugin.getShopManager().getActions().get(e.getPlayer().getUniqueId());
if (info == null) {
return;
}
final Player p = e.getPlayer();
final Location loc1 = info.getLocation();
final Location loc2 = p.getLocation();
if (loc1.getWorld() != loc2.getWorld() || loc1.distanceSquared(loc2) > 25) {
if (info.getAction() == ShopAction.BUY) {
MsgUtil.sendMessage(p, MsgUtil.getMessage("shop-purchase-cancelled", p));
Util.debugLog(p.getName() + " too far with the shop location.");
} else if (info.getAction() == ShopAction.CREATE) {
MsgUtil.sendMessage(p, MsgUtil.getMessage("shop-creation-cancelled", p));
Util.debugLog(p.getName() + " too far with the shop location.");
}
plugin.getShopManager().getActions().remove(p.getUniqueId());
}
}
/**
* Checks if players are far enough
* to set long distance flag to true
*
* @param location location
* @param players list of players
* @return long distance flag
*/
private static boolean isLongDistance(Location location, List<Player> players) {
String world = location.getWorld().getName();
Iterator i = players.iterator();
Location playerLocation;
do {
if(!i.hasNext()) {
return false;
}
Player player = (Player) i.next();
playerLocation = player.getLocation();
} while(!world.equals(playerLocation.getWorld().getName()) || playerLocation.distanceSquared(location) < 65536.0D);
return true;
}
public static ArmorStand getArmorStand(Location reactor, boolean createIfNoneExists) {
Location l = new Location(reactor.getWorld(), reactor.getX() + 0.5, reactor.getY() + 0.7, reactor.getZ() + 0.5);
for (Entity n : l.getChunk().getEntities()) {
if (n instanceof ArmorStand && l.distanceSquared(n.getLocation()) < 0.4D) {
return (ArmorStand) n;
}
}
if (!createIfNoneExists) {
return null;
}
ArmorStand hologram = SimpleHologram.create(l);
hologram.setCustomNameVisible(false);
hologram.setCustomName(null);
return hologram;
}
private static ArmorStand getArmorStand(Block projector, boolean createIfNoneExists) {
String nametag = BlockStorage.getLocationInfo(projector.getLocation(), "text");
double offset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), "offset"));
Location l = new Location(projector.getWorld(), projector.getX() + 0.5, projector.getY() + offset, projector.getZ() + 0.5);
for (Entity n : l.getChunk().getEntities()) {
if (n instanceof ArmorStand && n.getCustomName() != null && n.getCustomName().equals(nametag) && l.distanceSquared(n.getLocation()) < 0.4D) {
return (ArmorStand) n;
}
}
if (!createIfNoneExists) {
return null;
}
ArmorStand hologram = SimpleHologram.create(l);
hologram.setCustomName(nametag);
return hologram;
}
private void removeEntities(Location origin, double radius) {
if (radius <= 0) return;
double radiusSq = radius * radius;
for (Entity ent : origin.getWorld().getEntities()) {
if (origin.distanceSquared(ent.getLocation()) > radiusSq) continue;
if (ent instanceof TNTPrimed) {
ent.remove();
}
}
}
public static @Nullable <T extends Entity> T getClosestEntity(Location location, Vector range, final Class<T> type) {
T closest = null;
double minDistanceSquared = Double.POSITIVE_INFINITY;
for(Entity entity : location.getWorld().getNearbyEntities(location, range.getX(), range.getY(), range.getZ())) {
if(type.isInstance(entity)) {
double distanceSquared = location.distanceSquared(entity.getLocation());
if(distanceSquared < minDistanceSquared) {
minDistanceSquared = distanceSquared;
closest = type.cast(entity);
}
}
}
return closest;
}
private void removeEntities(Location origin, double radius) {
if(radius <= 0) return;
double radiusSq = radius * radius;
for(Entity ent : origin.getWorld().getEntities()) {
if(origin.distanceSquared(ent.getLocation()) > radiusSq)
continue;
if(ent instanceof TNTPrimed) {
ent.remove();
}
}
}
/**
* Uses the player's location subtracted from a nearby player's location and
* then gets angle with Vector#dot().
*
* @param player Player to check for direction.
* @return Gets target player by using all players within a radius of six blocks
* from the given player.
*/
public static Player getTargetPlayer(Player player)
{
Location location = player.getLocation();
Player targetPlayer = null;
List<Player> nearbyPlayers = new ArrayList<Player>();
for(Player p : Bukkit.getOnlinePlayers())
{
if(player.getWorld() != p.getWorld())
{
continue;
}
if(location.distanceSquared(p.getLocation()) > 36 || player.getName().equals(p.getName()))
{
continue;
}
Vector targetVector = p.getLocation().toVector().subtract(location.toVector()).normalize();
if(Math.round(targetVector.dot(location.getDirection())) == 1)
{
targetPlayer = p;
break;
}
}
return targetPlayer;
}
@Override
protected int process(User user, PacketEvent packetEvent)
{
final WrapperPlayClientPositionLook clientPositionLookWrapper = new WrapperPlayClientPositionLook(packetEvent.getPacket());
// Only check if the player has been teleported recently
if (user.hasTeleportedRecently(1000) &&
// World changes and respawns are exempted
!user.hasRespawnedRecently(2500) &&
!user.hasChangedWorldsRecently(2500) &&
// Lag occurrences after login.
!user.hasLoggedInRecently(10000))
{
// The position packet might not be exactly the same position.
// Squared values of 10, 5 and 3
final double allowedDistanceSquared = user.getPlayer().isFlying() ?
100 :
(user.getPlayer().isSprinting() ? 25 : 9);
final Location forcedLocation = (Location) user.getDataMap().getValue(DataKey.PACKET_ANALYSIS_LAST_POSITION_FORCE_LOCATION);
if (forcedLocation.getWorld().getUID().equals(user.getPlayer().getWorld().getUID())) {
final double distanceSquared = forcedLocation.distanceSquared(clientPositionLookWrapper.getLocation(user.getPlayer().getWorld()));
if (distanceSquared > allowedDistanceSquared) {
VerboseSender.getInstance().sendVerboseMessage("PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " tried to spoof position packets. | DS: " + distanceSquared + " ADS: " + allowedDistanceSquared);
return 10;
}
} else {
VerboseSender.getInstance().sendVerboseMessage("PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " diff world.");
}
}
return 0;
}
/**
* Gets the squared distance of two {@link Location}s, correctly handling cross-world requests.
*
* @return the squared distance of the two {@link Location}s or {@link Double#POSITIVE_INFINITY} if they are from different worlds.
*/
public static double safeWorldDistanceSquared(final Location firstLocation, final Location secondLocation)
{
return firstLocation.getWorld().getUID().equals(secondLocation.getWorld().getUID()) ?
firstLocation.distanceSquared(secondLocation) :
Double.POSITIVE_INFINITY;
}
/**
* Convenience method to check if a location is inside the border
* @param location The location to check
* @return True if it is inside (or there is no border), false if not
*/
default boolean isInsideBorder(Location location) {
Location center = getCenter(location.getWorld());
if (center != null) {
double radius = getBorderRadius(location.getWorld());
if (radius > 0) {
return center.distanceSquared(location) <= radius * radius;
}
}
return true;
}
@EventHandler
public void onTeleport(PlayerTeleportEvent event) {
final Player player = event.getPlayer();
VirtualWorld gen = getGenerator(player);
if (gen != null) {
Location from = event.getFrom();
Location to = event.getTo();
if (to.getWorld().equals(from.getWorld()) && to.distanceSquared(from) < 8) {
event.setTo(player.getLocation());
event.setCancelled(true);
player.setVelocity(player.getVelocity());
}
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof ConsoleCommandSender) {
HandleHelpPage(sender, 1);
return true;
}
Player player = (Player) sender;
String claimmode = RedProtect.get().config.getWorldClaimType(player.getWorld().getName());
if (!claimmode.equalsIgnoreCase("WAND") && !claimmode.equalsIgnoreCase("BOTH") && !RedProtect.get().ph.hasCommandPerm(player, "redefine")) {
return true;
}
if (args.length == 0) {
Location pl = player.getLocation();
RedProtect.get().firstLocationSelections.put(player, pl);
player.sendMessage(RedProtect.get().lang.get("playerlistener.wand1") + RedProtect.get().lang.get("general.color") + " (" + ChatColor.GOLD + pl.getBlockX() + RedProtect.get().lang.get("general.color") + ", " + ChatColor.GOLD + pl.getBlockY() + RedProtect.get().lang.get("general.color") + ", " + ChatColor.GOLD + pl.getBlockZ() + RedProtect.get().lang.get("general.color") + ").");
//show preview border
if (RedProtect.get().firstLocationSelections.containsKey(player) && RedProtect.get().secondLocationSelections.containsKey(player)) {
Location loc1 = RedProtect.get().firstLocationSelections.get(player);
Location loc2 = RedProtect.get().secondLocationSelections.get(player);
if (RedProtect.get().hooks.worldEdit && RedProtect.get().config.configRoot().hooks.useWECUI) {
WEHook.setSelectionRP(player, loc1, loc2);
}
if (loc1.getWorld().equals(loc2.getWorld()) && loc1.distanceSquared(loc2) > RedProtect.get().config.configRoot().region_settings.max_scan) {
double dist = loc1.distanceSquared(loc2);
RedProtect.get().lang.sendMessage(player, String.format(RedProtect.get().lang.get("regionbuilder.selection.maxdefine"), RedProtect.get().config.configRoot().region_settings.max_scan, (int) dist));
} else {
RedProtect.get().getUtil().addBorder(player, new Region("", loc1, loc2, player.getWorld().getName()));
}
}
return true;
}
RedProtect.get().lang.sendCommandHelp(sender, "pos1", true);
return true;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof ConsoleCommandSender) {
HandleHelpPage(sender, 1);
return true;
}
Player player = (Player) sender;
String claimmode = RedProtect.get().config.getWorldClaimType(player.getWorld().getName());
if (!claimmode.equalsIgnoreCase("WAND") && !claimmode.equalsIgnoreCase("BOTH") && !RedProtect.get().ph.hasCommandPerm(player, "redefine")) {
return true;
}
if (args.length == 0) {
Location pl = player.getLocation();
RedProtect.get().secondLocationSelections.put(player, pl);
player.sendMessage(RedProtect.get().lang.get("playerlistener.wand2") + RedProtect.get().lang.get("general.color") + " (" + ChatColor.GOLD + pl.getBlockX() + RedProtect.get().lang.get("general.color") + ", " + ChatColor.GOLD + pl.getBlockY() + RedProtect.get().lang.get("general.color") + ", " + ChatColor.GOLD + pl.getBlockZ() + RedProtect.get().lang.get("general.color") + ").");
//show preview border
if (RedProtect.get().firstLocationSelections.containsKey(player) && RedProtect.get().secondLocationSelections.containsKey(player)) {
Location loc1 = RedProtect.get().firstLocationSelections.get(player);
Location loc2 = RedProtect.get().secondLocationSelections.get(player);
if (RedProtect.get().hooks.worldEdit && RedProtect.get().config.configRoot().hooks.useWECUI) {
WEHook.setSelectionRP(player, loc1, loc2);
}
if (loc1.getWorld().equals(loc2.getWorld()) && loc1.distanceSquared(loc2) > RedProtect.get().config.configRoot().region_settings.max_scan && !RedProtect.get().ph.hasPerm(player, "redprotect.bypass.define-max-distance")) {
double dist = loc1.distanceSquared(loc2);
RedProtect.get().lang.sendMessage(player, String.format(RedProtect.get().lang.get("regionbuilder.selection.maxdefine"), RedProtect.get().config.configRoot().region_settings.max_scan, (int) dist));
} else {
RedProtect.get().getUtil().addBorder(player, new Region("", loc1, loc2, player.getWorld().getName()));
}
}
return true;
}
RedProtect.get().lang.sendCommandHelp(sender, "pos2", true);
return true;
}
private static ArmorStand getArmorStand(Block b, boolean createIfNoneExists) {
Location l = new Location(b.getWorld(), b.getX() + 0.5, b.getY() + 0.7F, b.getZ() + 0.5);
for (Entity n : l.getChunk().getEntities()) {
if (n instanceof ArmorStand && n.getCustomName() != null && l.distanceSquared(n.getLocation()) < 0.4D) {
return (ArmorStand) n;
}
}
if (!createIfNoneExists) return null;
else return create(l);
}
@Override
public void run() {
for (World world : Bukkit.getServer().getWorlds()) {
for (Player player : world.getPlayers()) {
final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
final GDPermissionUser holder = PermissionHolderCache.getInstance().getOrCreateUser(player);
final int accrualPerHour = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Integer.class), holder, Options.BLOCKS_ACCRUED_PER_HOUR, claim).intValue();
if (accrualPerHour > 0) {
Location lastLocation = playerData.lastAfkCheckLocation;
// if he's not in a vehicle and has moved at least three blocks since the last check and he's not being pushed around by fluids
if (player.getVehicle() == null &&
(lastLocation == null || lastLocation.getWorld() != player.getWorld() || lastLocation.distanceSquared(player.getLocation()) >= 0) &&
!NMSUtil.getInstance().isBlockWater(player.getLocation().getBlock())) {
int accruedBlocks = playerData.getBlocksAccruedPerHour() / 12;
if (accruedBlocks < 0) {
accruedBlocks = 1;
}
if (GriefDefenderPlugin.getInstance().isEconomyModeEnabled()) {
final VaultProvider vaultProvider = GriefDefenderPlugin.getInstance().getVaultProvider();
if (!vaultProvider.hasAccount(player)) {
continue;
}
vaultProvider.depositPlayer(player, accruedBlocks);
} else {
int currentTotal = playerData.getAccruedClaimBlocks();
if ((currentTotal + accruedBlocks) > playerData.getMaxAccruedClaimBlocks()) {
playerData.setAccruedClaimBlocks(playerData.getMaxAccruedClaimBlocks());
playerData.lastAfkCheckLocation = player.getLocation();
return;
}
playerData.setAccruedClaimBlocks(playerData.getAccruedClaimBlocks() + accruedBlocks);
}
}
playerData.lastAfkCheckLocation = player.getLocation();
}
}
}
}
@Override
protected void check(MoveEvent event) {
Location locTo = event.getTo();
Location locFrom = event.getFrom();
Player p = event.getPlayer();
HawkPlayer pp = event.getHawkPlayer();
if(!locFrom.getWorld().equals(locTo.getWorld()))
return;
//this stops an NPE
double distanceSquared = locFrom.distanceSquared(locTo);
if (distanceSquared == 0)
return;
double horizDistanceSquared = Math.pow(locTo.getX() - locFrom.getX(), 2) + Math.pow(locTo.getZ() - locFrom.getZ(), 2);
double vertDistance = Math.abs(locTo.getY() - locFrom.getY());
Vector moveDirection = new Vector(locTo.getX() - locFrom.getX(), locTo.getY() - locFrom.getY(), locTo.getZ() - locFrom.getZ());
AABB playerFrom = WrappedEntity.getWrappedEntity(p).getCollisionBox(locFrom.toVector());
playerFrom.shrink(SIDE_EPSILON, 0, SIDE_EPSILON);
playerFrom.getMin().setY(playerFrom.getMin().getY() + BOTTOM_EPSILON);
playerFrom.getMax().setY(playerFrom.getMax().getY() - TOP_EPSILON);
AABB playerTo = playerFrom.clone();
playerTo.translate(moveDirection);
Vector minBigBox = new Vector(Math.min(playerFrom.getMin().getX(), playerTo.getMin().getX()), Math.min(playerFrom.getMin().getY(), playerTo.getMin().getY()), Math.min(playerFrom.getMin().getZ(), playerTo.getMin().getZ()));
Vector maxBigBox = new Vector(Math.max(playerFrom.getMax().getX(), playerTo.getMax().getX()), Math.max(playerFrom.getMax().getY(), playerTo.getMax().getY()), Math.max(playerFrom.getMax().getZ(), playerTo.getMax().getZ()));
AABB bigBox = new AABB(minBigBox, maxBigBox);
AABB selection = bigBox.clone();
selection.getMin().setY(selection.getMin().getY() - 0.6); //we need to grab blocks below us too, such as fences
Set<Location> ignored = pp.getIgnoredBlockCollisions();
GameMode gm = p.getGameMode();
if(gm == GameMode.SURVIVAL || gm == GameMode.ADVENTURE || gm == GameMode.CREATIVE) {
for (int x = selection.getMin().getBlockX(); x <= selection.getMax().getBlockX(); x++) {
for (int y = selection.getMin().getBlockY(); y <= selection.getMax().getBlockY(); y++) {
for (int z = selection.getMin().getBlockZ(); z <= selection.getMax().getBlockZ(); z++) {
Location blockLoc = new Location(locTo.getWorld(), x, y, z);
//Skip block if it updated within player AABB (only if they move slowly)
if(ignored.contains(blockLoc) && horizDistanceSquared <= HORIZONTAL_DISTANCE_THRESHOLD && vertDistance <= VERTICAL_DISTANCE_THRESHOLD)
continue;
Block bukkitBlock = ServerUtils.getBlockAsync(blockLoc);
if (bukkitBlock == null)
continue;
WrappedBlock block = WrappedBlock.getWrappedBlock(bukkitBlock, pp.getClientVersion());
if (!block.isSolid())
continue;
if(bukkitBlock.getType() == Material.PISTON_MOVING_PIECE) {
continue;
}
if (bukkitBlock.getState().getData() instanceof Openable && horizDistanceSquared <= HORIZONTAL_DISTANCE_THRESHOLD && vertDistance <= VERTICAL_DISTANCE_THRESHOLD) {
continue;
}
for (AABB test : block.getCollisionBoxes()) {
//check if "test" box is even in "bigBox"
if (!test.isColliding(bigBox))
continue;
boolean xCollide = collides2d(test.getMin().getZ(), test.getMax().getZ(), test.getMin().getY(), test.getMax().getY(), playerFrom.getMin().getZ(), playerFrom.getMax().getZ(), playerFrom.getMin().getY(), playerFrom.getMax().getY(), moveDirection.getZ(), moveDirection.getY());
boolean yCollide = collides2d(test.getMin().getX(), test.getMax().getX(), test.getMin().getZ(), test.getMax().getZ(), playerFrom.getMin().getX(), playerFrom.getMax().getX(), playerFrom.getMin().getZ(), playerFrom.getMax().getZ(), moveDirection.getX(), moveDirection.getZ());
boolean zCollide = collides2d(test.getMin().getX(), test.getMax().getX(), test.getMin().getY(), test.getMax().getY(), playerFrom.getMin().getX(), playerFrom.getMax().getX(), playerFrom.getMin().getY(), playerFrom.getMax().getY(), moveDirection.getX(), moveDirection.getY());
if (xCollide && yCollide && zCollide) {
punish(pp, false, event, new Placeholder("block", bukkitBlock.getType()));
tryRubberband(event);
return;
}
}
}
}
}
}
reward(pp);
}
@Override
public Set<?> getTargets() {
Set<LivingEntity> returnSet = new HashSet<LivingEntity>();
int level = getLevel();
ConfigurationSection config = getConfig();
Entity origin = getOrigin();
if (!(origin instanceof LivingEntity)) {
return returnSet;
}
LivingEntity player = (LivingEntity) origin;
int range = (int) Math.round(Spell.getLevelAdjustedValue(config.getString("range","15"), level, null, null));
boolean pen = config.getBoolean("penetration", true);
boolean allowMultiple = config.getBoolean("allow-multiple", false);
Location observerPos = player.getEyeLocation();
Vector3D observerDir = new Vector3D(observerPos.getDirection());
Vector3D observerStart = new Vector3D(observerPos);
Vector3D observerEnd = observerStart.add(observerDir.multiply(range));
double closestDistance = 999999999;
HashSet<Material> materialHashSet = new HashSet<>();
Location wallLocation = player.getTargetBlock(materialHashSet, range).getLocation();
double wallDistance = player.getLocation().distanceSquared(wallLocation);
// Get nearby entities
for (Entity target : player.getNearbyEntities(range, range, range)) {
// Bounding box of the given player
Vector3D targetPos = new Vector3D(target.getLocation());
Vector3D minimum = targetPos.add(-0.5, 0, -0.5);
Vector3D maximum = targetPos.add(0.5, 1.67, 0.5);
if (target != player &&
Vector3D.hasIntersection(observerStart, observerEnd, minimum, maximum) &&
target instanceof LivingEntity) {
if (!pen && player.getLocation().distanceSquared(target.getLocation()) > wallDistance) {
continue;
}
if (!allowMultiple) {
double currentDistance = observerPos.distanceSquared(target.getLocation());
if (closestDistance < currentDistance) {
continue;
} else {
closestDistance = currentDistance;
returnSet.clear();
}
}
returnSet.add((LivingEntity) target);
}
}
return returnSet;
}
public static List<Entity> getNearbyEntities(Location location, double radius, EntityType... types) {
List<Entity> entities = new ArrayList<Entity>();
if (location == null) return entities;
if (radius <= 0.0D) return entities;
double radius2 = radius * radius;
int chunkRadius = ((int) (radius / 16)) + 1;
Chunk center = location.getChunk();
int startX = center.getX() - chunkRadius;
int endX = center.getX() + chunkRadius;
int startZ = center.getZ() - chunkRadius;
int endZ = center.getZ() + chunkRadius;
World world = location.getWorld();
for (int chunkX = startX; chunkX <= endX; chunkX++) {
for (int chunkZ = startZ; chunkZ <= endZ; chunkZ++) {
if (!world.isChunkLoaded(chunkX, chunkZ)) continue;
Chunk chunk = world.getChunkAt(chunkX, chunkZ);
for (Entity entity : chunk.getEntities()) {
Location entityLoc = entity.getLocation();
// TODO: this is a workaround: for some yet unknown reason entities sometimes report to be in a
// different world..
if (!entityLoc.getWorld().equals(world)) {
Log.debug("Found an entity which reports to be in a different world than the chunk we got it from:");
Log.debug("Location=" + location + ", Chunk=" + chunk + ", ChunkWorld=" + chunk.getWorld()
+ ", entityType=" + entity.getType() + ", entityLocation=" + entityLoc);
continue; // skip this entity
}
if (entityLoc.distanceSquared(location) <= radius2) {
if (types == null) {
entities.add(entity);
} else {
EntityType type = entity.getType();
for (EntityType t : types) {
if (type.equals(t)) {
entities.add(entity);
break;
}
}
}
}
}
}
}
return entities;
}
/**
* Simple method to know if a {@link Location} is close to another {@link Location}
*
* @param firstLocation the first {@link Location}
* @param secondLocation the second {@link Location}
* @param squaredDistance the squared distance that must be at most between the two {@link Location}s to make this {@link java.lang.reflect.Method} return true.
*
* @return true if the {@link Location} are in range, false if not
*/
public static boolean areLocationsInRange(final Location firstLocation, final Location secondLocation, final double squaredDistance)
{
return firstLocation.getWorld().getUID().equals(secondLocation.getWorld().getUID()) &&
firstLocation.distanceSquared(secondLocation) <= squaredDistance;
}