| 1 | package net.minecraft.world.entity.ai.behavior;
|
| 2 |
|
| 3 | import java.util.Optional;
|
| 4 | import java.util.function.Function;
|
| 5 | import net.minecraft.core.BlockPos;
|
| 6 | import net.minecraft.world.entity.Entity;
|
| 7 | import net.minecraft.world.entity.PathfinderMob;
|
| 8 | import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder;
|
| 9 | import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
| 10 | import net.minecraft.world.entity.ai.memory.WalkTarget;
|
| 11 | import net.minecraft.world.entity.ai.util.LandRandomPos;
|
| 12 | import net.minecraft.world.phys.Vec3;
|
| 13 |
|
| 14 | public class SetWalkTargetAwayFrom {
|
| 15 | public static BehaviorControl<PathfinderMob> pos(
|
| 16 | final MemoryModuleType<BlockPos> memory, final float speedModifier, final int desiredDistance, final boolean interruptCurrentWalk
|
| 17 | ) {
|
| 18 | return create(memory, speedModifier, desiredDistance, interruptCurrentWalk, Vec3::atBottomCenterOf);
|
| 19 | }
|
| 20 |
|
| 21 | public static OneShot<PathfinderMob> entity(
|
| 22 | final MemoryModuleType<? extends Entity> memory, final float speedModifier, final int desiredDistance, final boolean interruptCurrentWalk
|
| 23 | ) {
|
| 24 | return create(memory, speedModifier, desiredDistance, interruptCurrentWalk, Entity::position);
|
| 25 | }
|
| 26 |
|
| 27 | private static <T> OneShot<PathfinderMob> create(
|
| 28 | final MemoryModuleType<T> walkAwayFromMemory,
|
| 29 | final float speedModifier,
|
| 30 | final int desiredDistance,
|
| 31 | final boolean interruptCurrentWalk,
|
| 32 | final Function<T, Vec3> toPosition
|
| 33 | ) {
|
| 34 | return BehaviorBuilder.create(
|
| 35 | i -> i.group(i.registered(MemoryModuleType.WALK_TARGET), i.present(walkAwayFromMemory)).apply(i, (walkTarget, walkAwayFrom) -> (level, body, timestamp) -> {
|
| 36 | Optional<WalkTarget> target = i.tryGet(walkTarget);
|
| 37 | if (target.isPresent() && !interruptCurrentWalk) {
|
| 38 | return false;
|
| 39 | }
|
| 40 |
|
| 41 | Vec3 bodyPosition = body.position();
|
| 42 | Vec3 avoidPosition = toPosition.apply(i.get(walkAwayFrom));
|
| 43 | if (!bodyPosition.closerThan(avoidPosition, desiredDistance)) {
|
| 44 | return false;
|
| 45 | }
|
| 46 |
|
| 47 | if (target.isPresent() && target.get().getSpeedModifier() == speedModifier) {
|
| 48 | Vec3 currentDirection = target.get().getTarget().currentPosition().subtract(bodyPosition);
|
| 49 | Vec3 avoidDirection = avoidPosition.subtract(bodyPosition);
|
| 50 | if (currentDirection.dot(avoidDirection) < 0.0) {
|
| 51 | return false;
|
| 52 | }
|
| 53 | }
|
| 54 |
|
| 55 | for (int j = 0; j < 10; j++) {
|
| 56 | Vec3 fleeToPos = LandRandomPos.getPosAway(body, 16, 7, avoidPosition);
|
| 57 | if (fleeToPos != null) {
|
| 58 | walkTarget.set(new WalkTarget(fleeToPos, speedModifier, 0));
|
| 59 | break;
|
| 60 | }
|
| 61 | }
|
| 62 |
|
| 63 | return true;
|
| 64 | })
|
| 65 | );
|
| 66 | }
|
| 67 | }
|
| 68 |
|