| 1 | package net.minecraft.world.entity.ai.behavior;
|
| 2 |
|
| 3 | import java.util.Optional;
|
| 4 | import net.minecraft.core.BlockPos;
|
| 5 | import net.minecraft.server.level.ServerLevel;
|
| 6 | import net.minecraft.util.RandomSource;
|
| 7 | import net.minecraft.world.entity.LivingEntity;
|
| 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.level.levelgen.Heightmap;
|
| 12 | import net.minecraft.world.phys.Vec3;
|
| 13 | import org.jspecify.annotations.Nullable;
|
| 14 |
|
| 15 | public class MoveToSkySeeingSpot {
|
| 16 | public static OneShot<LivingEntity> create(final float speedModifier) {
|
| 17 | return BehaviorBuilder.create(i -> i.group(i.absent(MemoryModuleType.WALK_TARGET)).apply(i, walkTarget -> (level, body, timestamp) -> {
|
| 18 | if (level.canSeeSky(body.blockPosition())) {
|
| 19 | return false;
|
| 20 | }
|
| 21 |
|
| 22 | Optional<Vec3> landPos = Optional.ofNullable(getOutdoorPosition(level, body));
|
| 23 | landPos.ifPresent(pos -> walkTarget.set(new WalkTarget(pos, speedModifier, 0)));
|
| 24 | return true;
|
| 25 | }));
|
| 26 | }
|
| 27 |
|
| 28 | private static @Nullable Vec3 getOutdoorPosition(final ServerLevel level, final LivingEntity body) {
|
| 29 | RandomSource random = body.getRandom();
|
| 30 | BlockPos pos = body.blockPosition();
|
| 31 |
|
| 32 | for (int i = 0; i < 10; i++) {
|
| 33 | BlockPos randomPos = pos.offset(random.nextInt(20) - 10, random.nextInt(6) - 3, random.nextInt(20) - 10);
|
| 34 | if (hasNoBlocksAbove(level, body, randomPos)) {
|
| 35 | return Vec3.atBottomCenterOf(randomPos);
|
| 36 | }
|
| 37 | }
|
| 38 |
|
| 39 | return null;
|
| 40 | }
|
| 41 |
|
| 42 | public static boolean hasNoBlocksAbove(final ServerLevel level, final LivingEntity body, final BlockPos target) {
|
| 43 | return level.canSeeSky(target) && level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, target).getY() <= body.getY();
|
| 44 | }
|
| 45 | }
|
| 46 |
|