Caching entity target found by goal selectors

This commit is contained in:
Konstantin Shandurenko 2021-02-22 07:33:11 +03:00
parent 85a8396c9d
commit 54da48fd3e
2 changed files with 20 additions and 15 deletions

View File

@ -60,6 +60,23 @@ public abstract class GoalSelector {
return null; return null;
} }
/**
* Finds a target for an entity.
* If the current one is not present, falls back to {@link GoalSelector#findTarget()}
* and updates the target inside the entity.
*
* @return the target entity, null if not found
*/
@Nullable
public Entity findAndUpdateTarget() {
Entity target = entityCreature.getTarget();
if (target == null) {
target = findTarget();
entityCreature.setTarget(target);
}
return target;
}
/** /**
* Gets the entity behind the goal selector. * Gets the entity behind the goal selector.
* *

View File

@ -40,12 +40,12 @@ public class MeleeAttackGoal extends GoalSelector {
@Override @Override
public boolean shouldStart() { public boolean shouldStart() {
return getTarget() != null; return findAndUpdateTarget() != null;
} }
@Override @Override
public void start() { public void start() {
final Entity target = getTarget(); final Entity target = findAndUpdateTarget();
Check.notNull(target, "The target is not expected to be null!"); Check.notNull(target, "The target is not expected to be null!");
final Position targetPosition = target.getPosition(); final Position targetPosition = target.getPosition();
entityCreature.getNavigator().setPathTo(targetPosition); entityCreature.getNavigator().setPathTo(targetPosition);
@ -53,7 +53,7 @@ public class MeleeAttackGoal extends GoalSelector {
@Override @Override
public void tick(long time) { public void tick(long time) {
final Entity target = getTarget(); final Entity target = findAndUpdateTarget();
this.stop = target == null; this.stop = target == null;
@ -88,16 +88,4 @@ public class MeleeAttackGoal extends GoalSelector {
// Stop following the target // Stop following the target
entityCreature.getNavigator().setPathTo(null); entityCreature.getNavigator().setPathTo(null);
} }
/**
* Use {@link EntityCreature#getTarget()} or
* the entity target selectors to get the correct target
*
* @return the target of the entity
*/
@Nullable
private Entity getTarget() {
final Entity target = entityCreature.getTarget();
return target == null ? findTarget() : target;
}
} }