What we do know is that the Position
of the part is in the center. If we know the Size
of the part and divide it by 2, we can get the distance from the center. This is important because it gives us the Maximum
and Minimum
positions on where we want to spawn the Model
.
1 | local partSize = part.Size |
3 | local X_max = partSize.X/ 2 |
4 | local Z_max = partSize.Z/ 2 |
Now that we have the threshold values, how do we apply it to the model's position?
We have to account for the part's orientation. For this, we will use CFrame.lookVector
. This will give us the direction the part is looking forward. We will also need left and right, CFrame.rightVector
.
By turning the numbers negative, we can get its opposite direction of look
and right
to spawn them from the center of the part.
1 | local partCFrame = part.CFrame |
3 | local lookVector = partCFrame.lookVector |
4 | local rightVector = partCFrame.rightVector |
6 | local randomX = lookVector * math.random(-X_max, X_max) |
7 | local randomZ = rightVector * math.random(-Z_max, Z_max) |
This will randomly select an integer between those values and multiply it with the look direction as well as the right direction, matching the orientation of the part. Since these are just directions, it will only spawn them from the origin of the map (0, 0, 0).
We need to add the part's position to apply the direction that we randomly chose.
1 | local newPosition = part.Position + randomX + randomZ |
And there you have it! Good luck with your project!