"Look at Entity" prioritizes the nearest entity

This commit is contained in:
tanyaofei 2025-06-03 16:18:23 +08:00
parent 7997a36804
commit cd71977716

View File

@ -1,11 +1,15 @@
package io.github.hello09x.fakeplayer.core.entity.action.impl;
import com.google.common.collect.Iterables;
import io.github.hello09x.fakeplayer.api.spi.Action;
import io.github.hello09x.fakeplayer.api.spi.NMSServerPlayer;
import io.papermc.paper.entity.LookAnchor;
import org.bukkit.entity.Damageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
public class LookAtEntityAction implements Action {
@ -26,7 +30,12 @@ public class LookAtEntityAction implements Action {
return false;
}
bukkitPlayer.lookAt(Iterables.getFirst(entities, null), LookAnchor.EYES, LookAnchor.EYES);
var entity = this.getNearestEntity(bukkitPlayer, entities);
if (entity == null) {
return false;
}
bukkitPlayer.lookAt(entity, LookAnchor.EYES, LookAnchor.EYES);
player.resetLastActionTime();
return true;
}
@ -40,4 +49,25 @@ public class LookAtEntityAction implements Action {
public void stop() {
}
private @Nullable Entity getNearestEntity(@NotNull Player player, @NotNull Collection<? extends Entity> entities) {
if (entities.isEmpty()) {
return null;
}
var loc = player.getLocation();
Entity nearest = null;
double distance = 0;
for (var entity : entities) {
if (nearest == null) {
nearest = entity;
} else {
var d = loc.distance(entity.getLocation());
if (d < distance) {
nearest = entity;
distance = d;
}
}
}
return nearest;
}
}