| 1 | package net.minecraft.world.entity.ai.behavior;
|
| 2 |
|
| 3 | import java.util.Optional;
|
| 4 | import java.util.function.Predicate;
|
| 5 | import net.minecraft.util.RandomSource;
|
| 6 | import net.minecraft.util.valueproviders.UniformInt;
|
| 7 | import net.minecraft.world.entity.EntityType;
|
| 8 | import net.minecraft.world.entity.LivingEntity;
|
| 9 | import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder;
|
| 10 | import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
| 11 | import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities;
|
| 12 |
|
| 13 | @Deprecated
|
| 14 | public class SetEntityLookTargetSometimes {
|
| 15 | public static BehaviorControl<LivingEntity> create(final float maxDist, final UniformInt interval) {
|
| 16 | return create(maxDist, interval, mob -> true);
|
| 17 | }
|
| 18 |
|
| 19 | public static BehaviorControl<LivingEntity> create(final EntityType<?> type, final float maxDist, final UniformInt interval) {
|
| 20 | return create(maxDist, interval, mob -> mob.is(type));
|
| 21 | }
|
| 22 |
|
| 23 | private static BehaviorControl<LivingEntity> create(final float maxDist, final UniformInt interval, final Predicate<LivingEntity> predicate) {
|
| 24 | float maxDistSqr = maxDist * maxDist;
|
| 25 | SetEntityLookTargetSometimes.Ticker ticker = new SetEntityLookTargetSometimes.Ticker(interval);
|
| 26 | return BehaviorBuilder.create(
|
| 27 | i -> i.group(i.absent(MemoryModuleType.LOOK_TARGET), i.present(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES))
|
| 28 | .apply(
|
| 29 | i,
|
| 30 | (lookTarget, nearestEntities) -> (level, body, timestamp) -> {
|
| 31 | Optional<LivingEntity> target = i.<NearestVisibleLivingEntities>get(nearestEntities)
|
| 32 | .findClosest(predicate.and(mob -> mob.distanceToSqr(body) <= maxDistSqr));
|
| 33 | if (target.isEmpty()) {
|
| 34 | return false;
|
| 35 | }
|
| 36 |
|
| 37 | if (!ticker.tickDownAndCheck(level.getRandom())) {
|
| 38 | return false;
|
| 39 | }
|
| 40 |
|
| 41 | lookTarget.set(new EntityTracker(target.get(), true));
|
| 42 | return true;
|
| 43 | }
|
| 44 | )
|
| 45 | );
|
| 46 | }
|
| 47 |
|
| 48 | public static final class Ticker {
|
| 49 | private final UniformInt interval;
|
| 50 | private int ticksUntilNextStart;
|
| 51 |
|
| 52 | public Ticker(final UniformInt interval) {
|
| 53 | if (interval.minInclusive() <= 1) {
|
| 54 | throw new IllegalArgumentException();
|
| 55 | }
|
| 56 |
|
| 57 | this.interval = interval;
|
| 58 | }
|
| 59 |
|
| 60 | public boolean tickDownAndCheck(final RandomSource random) {
|
| 61 | if (this.ticksUntilNextStart == 0) {
|
| 62 | this.ticksUntilNextStart = this.interval.sample(random) - 1;
|
| 63 | return false;
|
| 64 | } else {
|
| 65 | return --this.ticksUntilNextStart == 0;
|
| 66 | }
|
| 67 | }
|
| 68 | }
|
| 69 | }
|
| 70 |
|