How do I spawn items within a radius of a position? [duplicate]
You can use the spreadplayers
command (which can spread entities as well). You will first need to summon the item somewhere and give it the tag teleport
which will be used to target it in the next command:
summon item x1 y1 z1 {Item:{id:"minecraft:gold_ingot",Count:1},Tags:[teleport]}
x1
and z1
are coordinates (that don't really matter).
Then, use this command to spread the item somewhere within a given area:
spreadplayers x2 z2 spreadDistance maxRange false @e[tag=teleport]
x2
and z2
are the coordinates of the centre of the area. spreadDistance
is the minimum distance between items (which only matters if there is more than one item that you're spawning at once). maxRange
is basically the radius but for a square instead of a circle.
As spreadplayers
teleports the items to the y-coordinate with a view of the sky, you may need to have a separate command to teleport them to the desired y-coordinate (if the y-coordinate doesn't have a view of the sky):
execute as @e[tag=teleport] at @s run tp ~ y ~
To make this occur randomly you can link a randomizer (a dropper one (permalink) will probably be sufficient) to a command block with the summon
command so that the command would activate randomly. Then add a chain command block next to the first command block with the spreadplayers
command. Add another chain command block with the third execute
command if it's required.
If you want to spawn multiple items at once, just add more command blocks to the chain (before the spreadplayers
one) with the same summon
command.
I haven't tested this but this should work.
Note (from the wiki (permalink)):
The spreadplayers command does not have a uniform distribution over the surface. It has a Gaussian distribution as the positions closer to the position set in the command have a higher chance of having an entity on them. This effect is very subtle and is not visible for short radius but can be a problem if you want a uniform random generation.