My ultimate goal is have NPCs that look at the nearest player, but look at a specified direction e.g. WEST
if no player is nearby. I obtained this code from Getting Nearest Entity and slightly altered it below.
public Entity getClosestDZNPC(Entity player) {
Entity closest = null;
double closestDistance = 0;
for (Entity entity : player.getLocation().getExtent().getEntities()) {
if (entity == player) {
continue;
}
double distance = entity.getLocation().getPosition().distance(player.getLocation().getPosition());
if (closest == null || distance < closestDistance) {
closest = entity;
closestDistance = distance;
}
}
return closest;
}
I then created a listener that would first find a player’s nearest NPC, then the NPC would find it’s nearest player and stare at them.
@Listener
public void onPlayerNearDZNPC(MoveEntityEvent event, @First Player player){
if(ArenaConfigUtils.getUserArenaNameFromLocation(player.getLocation())!=null){
if(ContestantConfigUtils.isUserAnArenaContestant(ArenaConfigUtils.getUserArenaNameFromLocation(player.getLocation()), player.getName())){
Entity nearestDZNPC = getClosestDZNPC(player);
Living NDZNPC = (Living)nearestDZNPC;
Entity nearestPlayer = getClosestDZNPC(nearestDZNPC);
double x = nearestPlayer.getLocation().getX();
double y = nearestPlayer.getLocation().getY();
double z = nearestPlayer.getLocation().getZ();
Vector3d V3D = new Vector3d(x,y,z);
NDZNPC.setHeadRotation(V3D);
nearestDZNPC.offer(Keys.SKIN_UNIQUE_ID, nearestPlayer.getUniqueId());
}
}
}
As of right now, the NPCs only seem to twitch their heads if a player is nearby.