Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Random Model Position Within A Part?

Asked by 5 years ago
Edited 5 years ago

Hey there! Currently what I have clones a model at the position of the spawner but what I want to do is make it spawn with a random X and Z value while being positioned within the spawn part. What do I do to randomize the position of the cloned model and make it clone multiple models simultaneously?

01math.randomseed(tick())
02 
03local seedSpawn = script.Parent
04local seeder = seedSpawn.Parent
05 
06while wait(0.25) do
07 
08    if seeder.SeederControl.CanPlant.Value == true and seeder.Parent.DriveSeat.Velocity.magnitude > 5 then
09 
10        local xPos = seedSpawn.Position.X
11        local yPos = seedSpawn.Position.Y
12        local zPos = seedSpawn.Position.Z
13 
14        local cornClone = game.ServerStorage.CornCrop:Clone()
15        cornClone.Parent = game.Workspace
View all 22 lines...
0
Use math.random(miniumvalue, maxiumvalue) MrOpScripter 81 — 5y

1 answer

Log in to vote
2
Answered by 5 years ago

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.

1local partSize = part.Size
2 
3local X_max = partSize.X/2
4local 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.

1local partCFrame = part.CFrame
2 
3local lookVector = partCFrame.lookVector
4local rightVector = partCFrame.rightVector
5 
6local randomX = lookVector * math.random(-X_max, X_max)
7local 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.

1local newPosition = part.Position + randomX + randomZ

And there you have it! Good luck with your project!

Ad

Answer this question