Java Code Examples for org.bukkit.entity.Player#getLocation()

The following examples show how to use org.bukkit.entity.Player#getLocation() . 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: SpawnUtil.java    From EchoPet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public EntityPet spawn(IPet pet, Player owner) {
    Location l = owner.getLocation();
    PetPreSpawnEvent spawnEvent = new PetPreSpawnEvent(pet, l);
    EchoPet.getPlugin().getServer().getPluginManager().callEvent(spawnEvent);
    if (spawnEvent.isCancelled()) {
        owner.sendMessage(EchoPet.getPrefix() + ChatColor.YELLOW + "Pet spawn was cancelled externally.");
        EchoPet.getManager().removePet(pet, true);
        return null;
    }
    l = spawnEvent.getSpawnLocation();
    World mcWorld = ((CraftWorld) l.getWorld()).getHandle();
    EntityPet entityPet = (EntityPet) pet.getPetType().getNewEntityPetInstance(mcWorld, pet);

    entityPet.setLocation(new Location(mcWorld.getWorld(), l.getX(), l.getY(), l.getZ(), l.getYaw(), l.getPitch()));
    if (!l.getChunk().isLoaded()) {
        l.getChunk().load();
    }
    if (!mcWorld.addEntity(entityPet, CreatureSpawnEvent.SpawnReason.CUSTOM)) {
        owner.sendMessage(EchoPet.getPrefix() + ChatColor.YELLOW + "Failed to spawn pet entity.");
        EchoPet.getManager().removePet(pet, true);
    } else {
        Particle.MAGIC_RUNES.builder().at(l).show();
    }
    return entityPet;
}
 
Example 2
Source File: SpawnUtil.java    From EchoPet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public EntityPet spawn(IPet pet, Player owner) {
    Location l = owner.getLocation();
    PetPreSpawnEvent spawnEvent = new PetPreSpawnEvent(pet, l);
    EchoPet.getPlugin().getServer().getPluginManager().callEvent(spawnEvent);
    if (spawnEvent.isCancelled()) {
        owner.sendMessage(EchoPet.getPrefix() + ChatColor.YELLOW + "Pet spawn was cancelled externally.");
        EchoPet.getManager().removePet(pet, true);
        return null;
    }
    l = spawnEvent.getSpawnLocation();
    World mcWorld = ((CraftWorld) l.getWorld()).getHandle();
    EntityPet entityPet = (EntityPet) pet.getPetType().getNewEntityPetInstance(mcWorld, pet);

    entityPet.setLocation(new Location(mcWorld.getWorld(), l.getX(), l.getY(), l.getZ(), l.getYaw(), l.getPitch()));
    if (!l.getChunk().isLoaded()) {
        l.getChunk().load();
    }
    if (!mcWorld.addEntity(entityPet, CreatureSpawnEvent.SpawnReason.CUSTOM)) {
        owner.sendMessage(EchoPet.getPrefix() + ChatColor.YELLOW + "Failed to spawn pet entity.");
        EchoPet.getManager().removePet(pet, true);
    } else {
        Particle.MAGIC_RUNES.builder().at(l).show();
    }
    return entityPet;
}
 
Example 3
Source File: TestWaypoints.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testAddWaypointToProfile() throws InterruptedException {
    Player player = server.addPlayer();
    PlayerProfile profile = TestUtilities.awaitProfile(player);

    Assertions.assertTrue(profile.getWaypoints().isEmpty());
    Waypoint waypoint = new Waypoint(profile, "hello", player.getLocation(), "HELLO");
    profile.addWaypoint(waypoint);
    Assertions.assertTrue(profile.isDirty());

    Assertions.assertThrows(IllegalArgumentException.class, () -> profile.addWaypoint(null));

    Assertions.assertFalse(profile.getWaypoints().isEmpty());
    Assertions.assertEquals(1, profile.getWaypoints().size());
    Assertions.assertEquals(waypoint, profile.getWaypoints().get(0));
}
 
Example 4
Source File: LegacySkinRefresher.java    From SkinsRestorerX with GNU General Public License v3.0 6 votes vote down vote up
@Override
@SneakyThrows
public void accept(Player player) {
    val vehicle = player.getVehicle();
    val handle = MH_GET_HANDLE.invoke(player);
    val location = player.getLocation();
    val world = location.getWorld();
    val dimension = MH_WORLD_DIMENSION.invoke(MH_GET_WORLD_HANDLE.invoke(world));
    MH_REREGISTER.invoke(player, handle);
    MH_MOVE_TO_WORLD.invoke(PLAYER_LIST, handle, dimension, false, location, false);
    if (vehicle != null) {
        vehicle.addPassenger(player);
    }
}
 
Example 5
Source File: VelocityTracker.java    From Sentinel with MIT License 6 votes vote down vote up
/**
 * Updates the velocity tracker for all players.
 */
public static void runAll() {
    for (Player player : Bukkit.getOnlinePlayers()) {
        VelocityTracker tracker = playerVelocityEstimates.get(player.getUniqueId());
        if (tracker == null) {
            tracker = new VelocityTracker();
            tracker.lastLocation = player.getLocation();
            playerVelocityEstimates.put(player.getUniqueId(), tracker);
        }
        if (player.getWorld().equals(tracker.lastLocation.getWorld())) {
            // This is an optimization hack to reduce object creation, because this loops often
            Location velocity = player.getLocation(locationOpti).subtract(tracker.lastLocation);
            tracker.velocity.setX(velocity.getX());
            tracker.velocity.setY(velocity.getY());
            tracker.velocity.setZ(velocity.getZ());
        }
        tracker.lastLocation = player.getLocation();
    }
}
 
Example 6
Source File: TpCommand.java    From MarriageMaster with GNU General Public License v3.0 5 votes vote down vote up
public void doTheTP(Player player, Player partner)
{
	if(player.canSee(partner))
	{
		if(!blacklistedWorlds.contains(partner.getLocation().getWorld().getName().toLowerCase()) || player.hasPermission(Permissions.BYPASS_WORLD_BLACKLIST))
		{
			Location loc = partner.getLocation();
			if(safetyCheck && (loc = getSaveLoc(loc)) == null)
			{
				messageUnsafe.send(player);
				messageToUnsafe.send(partner);
			}
			else
			{
				player.teleport(loc);
				messageTeleport.send(player);
				messageTeleportTo.send(partner);
			}
		}
		else
		{
			messageWorldNotAllowed.send(player);
		}
	}
	else
	{
		messagePartnerVanished.send(player);
	}
}
 
Example 7
Source File: SpectatorEvents.java    From Survival-Games with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerClickEvent(PlayerInteractEvent event) {
    Player player = event.getPlayer();
    try{
        if(GameManager.getInstance().isSpectator(player) && player.isSneaking() && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR)||
                GameManager.getInstance().isSpectator(player) && player.isSneaking() && (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_AIR)){
            Player[]players = GameManager.getInstance().getGame(GameManager.getInstance().getPlayerSpectateId(player)).getPlayers()[0];
            Game g = GameManager.getInstance().getGame(GameManager.getInstance().getPlayerSpectateId(player));

            int i = g.getNextSpec().get(player);
            if((event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR)){
                i++;
            }
            else if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_AIR){
                i--;
            }
            if(i>players.length-1){
                i = 0;
            }
            if(i<0){
                i = players.length-1;
            }
            g.getNextSpec().put(player, i);
            Player tpto = players[i];
            Location l = tpto.getLocation();
            l.setYaw(0);
            l.setPitch(0);
            player.teleport(l);
            player.sendMessage(ChatColor.AQUA+"You are now spectating "+tpto.getName());
        }
        else if (GameManager.getInstance().isSpectator(player)) {
            event.setCancelled(true);
        }
    }
    catch(Exception e){e.printStackTrace();}
}
 
Example 8
Source File: ExamineGui.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
private ItemStack locationItem(Player player)
{
	Location location = player.getLocation();
	
	ItemStack item = Items.builder()
			.setMaterial(Material.MAP).setAmount(1)
			.setName("&bLocation")
			.addLore(messages.examineLocation.replace("%location%", location.getWorld().getName() + " &8� &7" + JavaUtils.serializeLocation(location)))
			.build();
	
	return item;
}
 
Example 9
Source File: HomeTask.java    From Parties with GNU Affero General Public License v3.0 5 votes vote down vote up
public HomeTask(PartiesPlugin plugin, BukkitPartyPlayerImpl partyPlayer, Player player, long delayTime, Location homeLocation) {
	this.plugin = plugin;
	this.partyPlayer = partyPlayer;
	this.player = player;
	distanceLimitSquared = BukkitConfigParties.HOME_DISTANCE * BukkitConfigParties.HOME_DISTANCE;
	
	startTime = System.currentTimeMillis();
	startLocation = player.getLocation();
	
	this.delayTime = delayTime * 1000; // Get milliseconds instead of seconds
	this.homeLocation = homeLocation;
}
 
Example 10
Source File: TestWaypoints.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testWaypointAlreadyExisting() throws InterruptedException {
    Player player = server.addPlayer();
    PlayerProfile profile = TestUtilities.awaitProfile(player);

    Waypoint waypoint = new Waypoint(profile, "test", player.getLocation(), "Testing");
    profile.addWaypoint(waypoint);

    Assertions.assertEquals(1, profile.getWaypoints().size());
    Assertions.assertThrows(IllegalArgumentException.class, () -> profile.addWaypoint(waypoint));
    Assertions.assertEquals(1, profile.getWaypoints().size());
}
 
Example 11
Source File: Pos1Command.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 12
Source File: DebugCommand.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public void refreshchunk_cmd() throws CivException {
	Player you = getPlayer();
	ChunkCoord coord = new ChunkCoord(you.getLocation());
	
	for (Player player : Bukkit.getOnlinePlayers()) {
		player.getWorld().refreshChunk(coord.getX(), coord.getZ());
	}
}
 
Example 13
Source File: DebugFarmCommand.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public void cropcache_cmd() throws CivException {
	Player player = getPlayer();
	
	ChunkCoord coord = new ChunkCoord(player.getLocation());
	FarmChunk fc = CivGlobal.getFarmChunk(coord);
	if (fc == null) {
		throw new CivException("This is not a farm.");
	}
	
	for (BlockCoord bcoord : fc.cropLocationCache) {
		bcoord.getBlock().getWorld().playEffect(bcoord.getLocation(), Effect.MOBSPAWNER_FLAMES, 1);
	}
	CivMessage.sendSuccess(player, "Flashed cached crops.");
}
 
Example 14
Source File: Signs.java    From TabooLib with MIT License 5 votes vote down vote up
/**
 * 向玩家发送虚拟牌子,并返回编辑内容
 *
 * @param player  玩家
 * @param origin  原始内容
 * @param catcher 编辑内容
 */
public static void fakeSign(Player player, String[] origin, Consumer<String[]> catcher) {
    Validate.isTrue(Version.isAfter(Version.v1_8), "Unsupported Version: " + Version.getCurrentVersion());
    Location location = player.getLocation();
    location.setY(0);
    try {
        player.sendBlockChange(location, Materials.OAK_WALL_SIGN.parseMaterial(), (byte) 0);
        player.sendSignChange(location, format(origin));
    } catch (Throwable t) {
        t.printStackTrace();
    }
    NMS.handle().openSignEditor(player, location.getBlock());
    signs.add(new Data(player.getName(), catcher, location.getBlockX(), location.getBlockY(), location.getBlockZ()));
}
 
Example 15
Source File: GrapplingHookListener.java    From Slimefun4 with GNU General Public License v3.0 4 votes vote down vote up
private void handleGrapplingHook(Arrow arrow) {
    if (arrow != null && arrow.isValid() && arrow.getShooter() instanceof Player) {
        Player p = (Player) arrow.getShooter();
        GrapplingHookEntity hook = activeHooks.get(p.getUniqueId());

        if (hook != null) {
            Location target = arrow.getLocation();
            hook.drop(target);

            Vector velocity = new Vector(0.0, 0.2, 0.0);

            if (p.getLocation().distance(target) < 3.0) {
                if (target.getY() <= p.getLocation().getY()) {
                    velocity = target.toVector().subtract(p.getLocation().toVector());
                }
            }
            else {
                Location l = p.getLocation();
                l.setY(l.getY() + 0.5);
                p.teleport(l);

                double g = -0.08;
                double d = target.distance(l);
                double t = d;
                double vX = (1.0 + 0.08 * t) * (target.getX() - l.getX()) / t;
                double vY = (1.0 + 0.04 * t) * (target.getY() - l.getY()) / t - 0.5D * g * t;
                double vZ = (1.0 + 0.08 * t) * (target.getZ() - l.getZ()) / t;

                velocity = p.getVelocity();
                velocity.setX(vX);
                velocity.setY(vY);
                velocity.setZ(vZ);
            }

            p.setVelocity(velocity);

            hook.remove();
            Slimefun.runSync(() -> activeHooks.remove(p.getUniqueId()), 20L);
        }
    }
}
 
Example 16
Source File: ProjectileComponent.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
private boolean canSee(Player player, Location loc2) {
	Location loc1 = player.getLocation();		
	return ((CraftWorld)loc1.getWorld()).getHandle().a(Vec3D.a(loc1.getX(), loc1.getY() + player.getEyeHeight(), loc1.getZ()), Vec3D.a(loc2.getX(), loc2.getY(), loc2.getZ())) == null;
}
 
Example 17
Source File: Game.java    From Survival-Games with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public void killPlayer(Player p, boolean left) {
	try{
		clearInv(p);
		if (!left) {
			p.teleport(SettingsManager.getInstance().getLobbySpawn());
		}
		sm.playerDied(p, activePlayers.size(), gameID, new Date().getTime() - startTime);

		if (!activePlayers.contains(p)) return;
		else restoreInv(p);

		activePlayers.remove(p);
		inactivePlayers.add(p);
		PlayerKilledEvent pk = null;
		if (left) {
			msgFall(PrefixType.INFO, "game.playerleavegame","player-"+p.getName() );
		} else {
			if (mode != GameMode.WAITING && p.getLastDamageCause() != null && p.getLastDamageCause().getCause() != null) {
				switch (p.getLastDamageCause().getCause()) {
				case ENTITY_ATTACK:
					if(p.getLastDamageCause().getEntityType() == EntityType.PLAYER){
						Player killer = p.getKiller();
						msgFall(PrefixType.INFO, "death."+p.getLastDamageCause().getEntityType(),
								"player-"+(SurvivalGames.auth.contains(p.getName()) ? ChatColor.DARK_RED + "" + ChatColor.BOLD : "") + p.getName(),
								"killer-"+((killer != null)?(SurvivalGames.auth.contains(killer.getName()) ? ChatColor.DARK_RED + "" + ChatColor.BOLD : "") 
										+ killer.getName():"Unknown"),
										"item-"+((killer!=null)?ItemReader.getFriendlyItemName(killer.getItemInHand().getType()) : "Unknown Item"));
						if(killer != null && p != null)
							sm.addKill(killer, p, gameID);
						pk = new PlayerKilledEvent(p, this, killer, p.getLastDamageCause().getCause());
					}
					else{
						msgFall(PrefixType.INFO, "death."+p.getLastDamageCause().getEntityType(), "player-"
								+(SurvivalGames.auth.contains(p.getName()) ? ChatColor.DARK_RED + "" + ChatColor.BOLD : "") 
								+ p.getName(), "killer-"+p.getLastDamageCause().getEntityType());
						pk = new PlayerKilledEvent(p, this, null, p.getLastDamageCause().getCause());

					}
					break;
				default:
					msgFall(PrefixType.INFO, "death."+p.getLastDamageCause().getCause().name(), 
							"player-"+(SurvivalGames.auth.contains(p.getName()) ? ChatColor.DARK_RED + "" + ChatColor.BOLD : "") + p.getName(), 
							"killer-"+p.getLastDamageCause().getCause());
					pk = new PlayerKilledEvent(p, this, null, p.getLastDamageCause().getCause());

					break;
				}
				Bukkit.getServer().getPluginManager().callEvent(pk);

				if (getActivePlayers() > 1) {
					for (Player pl: getAllPlayers()) {
						msgmgr.sendMessage(PrefixType.INFO, ChatColor.DARK_AQUA + "There are " + ChatColor.YELLOW + "" 
								+ getActivePlayers() + ChatColor.DARK_AQUA + " players remaining!", pl);
					}
				}
			}

		}

		for (Player pe: activePlayers) {
			Location l = pe.getLocation();
			l.setY(l.getWorld().getMaxHeight());
			l.getWorld().strikeLightningEffect(l);
		}

		if (getActivePlayers() <= config.getInt("endgame.players") && config.getBoolean("endgame.fire-lighting.enabled") && !endgameRunning) {

			tasks.add(Bukkit.getScheduler().scheduleSyncRepeatingTask(GameManager.getInstance().getPlugin(),
					new EndgameManager(),
					0,
					config.getInt("endgame.fire-lighting.interval") * 20));
		}

		if (activePlayers.size() < 2 && mode != GameMode.WAITING) {
			playerWin(p);
			endGame();
		}
		LobbyManager.getInstance().updateWall(gameID);
		
	}catch (Exception e){
		SurvivalGames.$("???????????????????????");
		e.printStackTrace();
		SurvivalGames.$("ID"+gameID);
		SurvivalGames.$(left+"");
		SurvivalGames.$(activePlayers.size()+"");
		SurvivalGames.$(activePlayers.toString());
		SurvivalGames.$(p.getName());
		SurvivalGames.$(p.getLastDamageCause().getCause().name());
	}
}
 
Example 18
Source File: DGameWorld.java    From DungeonsXL with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Handles what happens when a player places a block.
 *
 * @param player
 * @param block
 * @param against
 * @param hand    the event parameters.
 * @return if the event is cancelled
 */
public boolean onPlace(Player player, Block block, Block against, ItemStack hand) {
    Game game = getGame();
    if (game == null) {
        return true;
    }

    PlaceableBlock placeableBlock = null;
    for (PlaceableBlock gamePlaceableBlock : placeableBlocks) {
        if (gamePlaceableBlock.canPlace(block, caliburn.getExItem(hand))) {
            placeableBlock = gamePlaceableBlock;
            break;
        }
    }
    if (!getRules().getState(GameRule.PLACE_BLOCKS) && placeableBlock == null) {
        // Workaround for a bug that would allow 3-Block-high jumping
        Location loc = player.getLocation();
        if (loc.getY() > block.getY() + 1.0 && loc.getY() <= block.getY() + 1.5) {
            if (loc.getX() >= block.getX() - 0.3 && loc.getX() <= block.getX() + 1.3) {
                if (loc.getZ() >= block.getZ() - 0.3 && loc.getZ() <= block.getZ() + 1.3) {
                    loc.setX(block.getX() + 0.5);
                    loc.setY(block.getY());
                    loc.setZ(block.getZ() + 0.5);
                    player.teleport(loc);
                }
            }
        }

        return true;
    }
    if (placeableBlock != null) {
        placeableBlock.onPlace();
    }

    Set<ExItem> whitelist = getRules().getState(GameRule.PLACE_WHITELIST);
    if (whitelist == null || whitelist.contains(VanillaItem.get(block.getType()))) {
        placedBlocks.add(block);
        return false;
    }

    return true;
}
 
Example 19
Source File: CombatLogTracker.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Get the cause of the player's imminent death, or null if they are not about to die NOTE: not
 * idempotent, has the side effect of clearing the recentDamage cache
 */
public @Nullable ImminentDeath getImminentDeath(Player player) {
  // If the player is already dead or in creative mode, we don't care
  if (player.isDead() || player.getGameMode() == GameMode.CREATIVE) return null;

  // If the player was on the ground, or is flying, or is able to fly, they are fine
  if (!(player.isOnGround() || player.isFlying() || player.getAllowFlight())) {
    // If the player is falling, detect an imminent falling death
    double fallDistance = player.getFallDistance();
    Block landingBlock = null;
    int waterDepth = 0;
    Location location = player.getLocation();

    if (location.getY() > 256) {
      // If player is above Y 256, assume they fell at least to there
      fallDistance += location.getY() - 256;
      location.setY(256);
    }

    // Search the blocks directly beneath the player until we find what they would have landed on
    Block block = null;
    for (; location.getY() >= 0; location.add(0, -1, 0)) {
      block = location.getBlock();
      if (block != null) {
        landingBlock = block;

        if (Materials.isWater(landingBlock.getType())) {
          // If the player falls through water, reset fall distance and inc the water depth
          fallDistance = -1;
          waterDepth += 1;

          // Break if they have fallen through enough water to stop falling
          if (waterDepth >= BREAK_FALL_WATER_DEPTH) break;
        } else {
          // If the block is not water, reset the water depth
          waterDepth = 0;

          if (Materials.isSolid(landingBlock.getType())
              || Materials.isLava(landingBlock.getType())) {
            // Break if the player hits a solid block or lava
            break;
          } else if (landingBlock.getType() == Material.WEB) {
            // If they hit web, reset their fall distance, but assume they keep falling
            fallDistance = -1;
          }
        }
      }

      fallDistance += 1;
    }

    double resistanceFactor = getResistanceFactor(player);
    boolean fireResistance = hasFireResistance(player);

    // Now decide if the landing would have killed them
    if (location.getBlockY() < 0) {
      // The player would have fallen into the void
      return new ImminentDeath(EntityDamageEvent.DamageCause.VOID, location, null, false);
    } else if (landingBlock != null) {
      if (Materials.isSolid(landingBlock.getType())
          && player.getHealth() <= resistanceFactor * (fallDistance - SAFE_FALL_DISTANCE)) {
        // The player would have landed on a solid block and taken enough fall damage to kill them
        return new ImminentDeath(
            EntityDamageEvent.DamageCause.FALL,
            landingBlock.getLocation().add(0, 0.5, 0),
            null,
            false);
      } else if (Materials.isLava(landingBlock.getType())
          && resistanceFactor > 0
          && !fireResistance) {
        // The player would have landed in lava, and we give the lava the benefit of the doubt
        return new ImminentDeath(
            EntityDamageEvent.DamageCause.LAVA, landingBlock.getLocation(), landingBlock, false);
      }
    }
  }

  // If we didn't predict a falling death, detect combat log due to recent damage
  Damage damage = this.recentDamage.remove(player);
  if (damage != null && damage.time.plus(RECENT_DAMAGE_THRESHOLD).isAfter(Instant.now())) {
    // Player logged out too soon after taking damage
    return new ImminentDeath(damage.event.getCause(), player.getLocation(), null, true);
  }

  return null;
}
 
Example 20
Source File: CreateCommand.java    From HolographicDisplays with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String label, String[] args) throws CommandException {
	Player player = CommandValidator.getPlayerSender(sender);
	String hologramName = args[0];

	if (!hologramName.matches("[a-zA-Z0-9_\\-]+")) {
		throw new CommandException("The name must contain only alphanumeric chars, underscores and hyphens.");
	}

	CommandValidator.isTrue(!NamedHologramManager.isExistingHologram(hologramName), "A hologram with that name already exists.");

	Location spawnLoc = player.getLocation();
	boolean moveUp = player.isOnGround();

	if (moveUp) {
		spawnLoc.add(0.0, 1.2, 0.0);
	}

	NamedHologram hologram = new NamedHologram(spawnLoc, hologramName);

	if (args.length > 1) {
		String text = Utils.join(args, " ", 1, args.length);
		CommandValidator.isTrue(!text.equalsIgnoreCase("{empty}"), "The first line should not be empty.");
		
		CraftHologramLine line = CommandValidator.parseHologramLine(hologram, text, true);
		hologram.getLinesUnsafe().add(line);
		player.sendMessage(Colors.SECONDARY_SHADOW + "(Change the lines with /" + label + " edit " + hologram.getName() + ")");
	} else {
		hologram.appendTextLine("Default hologram. Change it with " + Colors.PRIMARY + "/" + label + " edit " + hologram.getName());
	}

	NamedHologramManager.addHologram(hologram);
	hologram.refreshAll();

	HologramDatabase.saveHologram(hologram);
	HologramDatabase.trySaveToDisk();
	Location look = player.getLocation();
	look.setPitch(90);
	player.teleport(look, TeleportCause.PLUGIN);
	player.sendMessage(Colors.PRIMARY + "You created a hologram named '" + hologram.getName() + "'.");

	if (moveUp) {
		player.sendMessage(Colors.SECONDARY_SHADOW + "(You were on the ground, the hologram was automatically moved up. If you use /" + label + " movehere " + hologram.getName() + ", the hologram will be moved to your feet)");
	}
}