Minecraft – How to make mobs walk to other entities

minecraft-commandsminecraft-java-edition

I'm in Java 1.14.4 and I'm attempting to make all rabbit entities walk to a specific tagged item if they are in the range of it.

execute as @e[type=rabbit] at @s run teleport @s @e[tag=fruit,distance=5..25,limit=1]

This command would teleport any rabbits to that specific entity, but I was looking for something where the rabbit would slowly walk up to that destination instead. Is there a way to do this?

Best Answer

Since 1.14 this is possible relatively easily with the wandering trader. It has the WanderTarget NBT field that you can set to any coordinates to make it use its regular pathfinding to walk there.

You need the dummy scoreboards x, y and z.

/execute at @e[type=rabbit] run summon wandering_trader
/execute at @e[type=rabbit] store result entity @e[type=wandering_trader,distance=0,limit=1] WanderTarget.X int 1 run data get entity @e[tag=fruit,distance=5..25,limit=1] Pos[0]
/execute at @e[type=rabbit] store result entity @e[type=wandering_trader,distance=0,limit=1] WanderTarget.Y int 1 run data get entity @e[tag=fruit,distance=5..25,limit=1] Pos[1]
/execute at @e[type=rabbit] store result entity @e[type=wandering_trader,distance=0,limit=1] WanderTarget.Z int 1 run data get entity @e[tag=fruit,distance=5..25,limit=1] Pos[2]

Then you continuously teleport the rabbit to the wandering trader. When it's within about 2 blocks or so, kill the wandering trader.
The downside of this is that it won't hop. It will also not go exactly towards the target, because the wandering target stops about two blocks before its target coordinates. But maybe it's already good enough to teleport the rabbit the remaining distance. This system also only works properly at night, otherwise the wandering trader is visible. You could give it invisibility repeatedly, but then it will still show its milk bucket whenever it tries to get rid of the effect.

Thanks to "šŸ¾ Aelicorn_v2 šŸ¾" and "remy - 1.14" in the Minecraft commands Discord for their help with this answer (mainly the as vs. at confusion).