NPCLib/api/src/main/java/net/jitse/npclib/listeners/ChunkListener.java

89 lines
2.8 KiB
Java
Raw Normal View History

2018-04-26 13:52:49 +02:00
/*
* Copyright (c) 2018 Jitse Boonstra
*/
package net.jitse.npclib.listeners;
2019-08-03 13:47:12 +02:00
import net.jitse.npclib.NPCLib;
import net.jitse.npclib.internal.NPCManager;
import net.jitse.npclib.internal.SimpleNPC;
2018-04-26 13:52:49 +02:00
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import java.util.UUID;
/**
* @author Jitse Boonstras
*/
public class ChunkListener implements Listener {
2019-08-03 13:47:12 +02:00
private final NPCLib instance;
public ChunkListener(NPCLib instance) {
this.instance = instance;
}
2018-04-26 13:52:49 +02:00
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
Chunk chunk = event.getChunk();
2019-08-03 13:47:12 +02:00
for (SimpleNPC npc : NPCManager.getAllNPCs()) {
2018-04-26 13:52:49 +02:00
Chunk npcChunk = npc.getLocation().getChunk();
if (chunk.equals(npcChunk)) {
// Unloaded chunk with NPC in it. Hiding it from all players currently shown to.
for (UUID uuid : npc.getShown()) {
// Safety check so it doesn't send packets if the NPC has already
// been automatically despawned by the system.
if (npc.getAutoHidden().contains(uuid)) {
continue;
}
2018-05-06 23:34:55 +02:00
npc.hide(Bukkit.getPlayer(uuid), true, true);
2018-04-26 13:52:49 +02:00
}
}
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
Chunk chunk = event.getChunk();
2019-08-03 13:47:12 +02:00
for (SimpleNPC npc : NPCManager.getAllNPCs()) {
2018-04-26 13:52:49 +02:00
Chunk npcChunk = npc.getLocation().getChunk();
if (chunk.equals(npcChunk)) {
// Loaded chunk with NPC in it. Showing it to the players again.
for (UUID uuid : npc.getShown()) {
// Make sure not to respawn a not-hidden NPC.
if (!npc.getAutoHidden().contains(uuid)) {
continue;
}
Player player = Bukkit.getPlayer(uuid);
if (!npcChunk.getWorld().equals(player.getWorld())) {
continue; // Player and NPC are not in the same world.
}
2019-08-03 13:47:12 +02:00
double hideDistance = instance.getAutoHideDistance();
2018-04-26 13:52:49 +02:00
double distanceSquared = player.getLocation().distanceSquared(npc.getLocation());
boolean inRange = distanceSquared <= (hideDistance * hideDistance) || distanceSquared <= (Bukkit.getViewDistance() << 4);
// Show the NPC (if in range).
if (inRange) {
2018-05-11 01:45:12 +02:00
npc.show(player, true);
2018-04-26 13:52:49 +02:00
}
}
}
}
}
}