Correct Instance#getNearbyEntities implementation

This commit is contained in:
KrystilizeNevaDies 2021-09-16 14:56:08 +10:00
parent 2589cc4f3e
commit e061c1e640
3 changed files with 59 additions and 2 deletions

View File

@ -495,13 +495,27 @@ public abstract class Instance implements BlockGetter, BlockSetter, Tickable, Ta
int maxX = ChunkUtils.getChunkCoordinate(point.x() + range);
int minZ = ChunkUtils.getChunkCoordinate(point.z() - range);
int maxZ = ChunkUtils.getChunkCoordinate(point.z() + range);
// Cache squared range to prevent sqrt operations
double squaredRange = range * range;
List<Entity> result = new ArrayList<>();
synchronized (entitiesLock) {
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
Chunk chunk = getChunk(x, z);
if (chunk != null) {
result.addAll(getChunkEntities(chunk));
if (chunk == null) {
continue;
}
Set<Entity> chunkEntities = getChunkEntities(chunk);
// Filter all entities out of range
for (Entity chunkEntity : chunkEntities) {
if (point.distanceSquared(chunkEntity.getPosition()) < squaredRange) {
result.add(chunkEntity);
}
}
}
}

View File

@ -39,6 +39,7 @@ public class Main {
commandManager.register(new ShutdownCommand());
commandManager.register(new TeleportCommand());
commandManager.register(new PlayersCommand());
commandManager.register(new FindCommand());
commandManager.register(new PotionCommand());
commandManager.register(new TitleCommand());
commandManager.register(new BookCommand());
@ -50,6 +51,7 @@ public class Main {
commandManager.register(new GiveCommand());
commandManager.register(new SetBlockCommand());
commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED)));
MinecraftServer.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND));

View File

@ -0,0 +1,41 @@
package demo.commands;
import net.minestom.server.command.CommandSender;
import net.minestom.server.command.builder.Command;
import net.minestom.server.command.builder.CommandContext;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.Player;
import java.util.Collection;
import static net.minestom.server.command.builder.arguments.ArgumentType.*;
public class FindCommand extends Command {
public FindCommand() {
super("find");
this.addSyntax(
this::executorEntity,
Literal("entity"),
Float("range")
);
}
private void executorEntity(CommandSender sender, CommandContext context) {
Player player = sender.asPlayer();
float range = context.get("range");
Collection<Entity> entities = player.getInstance().getNearbyEntities(player.getPosition(), range);
player.sendMessage("Search result: ");
for (Entity entity : entities) {
player.sendMessage(" " + entity.getEntityType() + ": ");
player.sendMessage(" Meta: " + entity.getEntityMeta());
player.sendMessage(" Permissions: " + entity.getAllPermissions());
player.sendMessage(" Position: " + entity.getPosition());
}
player.sendMessage("End result.");
}
}