| 1 | package net.minecraft.world.entity.ai.behavior;
|
| 2 |
|
| 3 | import java.util.Optional;
|
| 4 | import net.minecraft.core.BlockPos;
|
| 5 | import net.minecraft.core.GlobalPos;
|
| 6 | import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder;
|
| 7 | import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
| 8 | import net.minecraft.world.entity.ai.memory.WalkTarget;
|
| 9 | import net.minecraft.world.entity.ai.util.DefaultRandomPos;
|
| 10 | import net.minecraft.world.entity.npc.villager.Villager;
|
| 11 | import net.minecraft.world.phys.Vec3;
|
| 12 |
|
| 13 | public class SetWalkTargetFromBlockMemory {
|
| 14 | public static OneShot<Villager> create(
|
| 15 | final MemoryModuleType<GlobalPos> memoryType,
|
| 16 | final float speedModifier,
|
| 17 | final int closeEnoughDist,
|
| 18 | final int tooFarDistance,
|
| 19 | final int tooLongUnreachableDuration
|
| 20 | ) {
|
| 21 | return BehaviorBuilder.create(
|
| 22 | i -> i.group(i.registered(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE), i.absent(MemoryModuleType.WALK_TARGET), i.present(memoryType))
|
| 23 | .apply(
|
| 24 | i,
|
| 25 | (cantReachSince, walkTarget, memory) -> (level, body, timestamp) -> {
|
| 26 | GlobalPos targetPos = i.get(memory);
|
| 27 | Optional<Long> cantReachTargetSince = i.tryGet(cantReachSince);
|
| 28 | if (targetPos.dimension() == level.dimension()
|
| 29 | && (!cantReachTargetSince.isPresent() || level.getGameTime() - cantReachTargetSince.get() <= tooLongUnreachableDuration)) {
|
| 30 | if (targetPos.pos().distManhattan(body.blockPosition()) > tooFarDistance) {
|
| 31 | Vec3 towardsTargetPos = null;
|
| 32 | int tries = 0;
|
| 33 | int MAX_TRIES = 1000;
|
| 34 |
|
| 35 | while (towardsTargetPos == null || BlockPos.containing(towardsTargetPos).distManhattan(body.blockPosition()) > tooFarDistance) {
|
| 36 | towardsTargetPos = DefaultRandomPos.getPosTowards(body, 15, 7, Vec3.atBottomCenterOf(targetPos.pos()), (float) (Math.PI / 2));
|
| 37 | if (++tries == 1000) {
|
| 38 | body.releasePoi(memoryType);
|
| 39 | memory.erase();
|
| 40 | cantReachSince.set(timestamp);
|
| 41 | return true;
|
| 42 | }
|
| 43 | }
|
| 44 |
|
| 45 | walkTarget.set(new WalkTarget(towardsTargetPos, speedModifier, closeEnoughDist));
|
| 46 | } else if (targetPos.pos().distManhattan(body.blockPosition()) > closeEnoughDist) {
|
| 47 | walkTarget.set(new WalkTarget(targetPos.pos(), speedModifier, closeEnoughDist));
|
| 48 | }
|
| 49 | } else {
|
| 50 | body.releasePoi(memoryType);
|
| 51 | memory.erase();
|
| 52 | cantReachSince.set(timestamp);
|
| 53 | }
|
| 54 |
|
| 55 | return true;
|
| 56 | }
|
| 57 | )
|
| 58 | );
|
| 59 | }
|
| 60 | }
|
| 61 |
|