Merge pull request #145 from RinesThaix/goalTargetsCaching

Caching entity target found by goal selectors
This commit is contained in:
TheMode 2021-02-22 05:36:26 +01:00 committed by GitHub
commit 1fda2aba6d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 15 deletions

View File

@ -60,6 +60,23 @@ public abstract class GoalSelector {
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.
*

View File

@ -40,12 +40,12 @@ public class MeleeAttackGoal extends GoalSelector {
@Override
public boolean shouldStart() {
return getTarget() != null;
return findAndUpdateTarget() != null;
}
@Override
public void start() {
final Entity target = getTarget();
final Entity target = findAndUpdateTarget();
Check.notNull(target, "The target is not expected to be null!");
final Position targetPosition = target.getPosition();
entityCreature.getNavigator().setPathTo(targetPosition);
@ -53,7 +53,7 @@ public class MeleeAttackGoal extends GoalSelector {
@Override
public void tick(long time) {
final Entity target = getTarget();
final Entity target = findAndUpdateTarget();
this.stop = target == null;
@ -88,16 +88,4 @@ public class MeleeAttackGoal extends GoalSelector {
// Stop following the target
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;
}
}