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?

math.randomseed(tick())

local seedSpawn = script.Parent
local seeder = seedSpawn.Parent

while wait(0.25) do

    if seeder.SeederControl.CanPlant.Value == true and seeder.Parent.DriveSeat.Velocity.magnitude > 5 then

        local xPos = seedSpawn.Position.X
        local yPos = seedSpawn.Position.Y
        local zPos = seedSpawn.Position.Z

        local cornClone = game.ServerStorage.CornCrop:Clone()
        cornClone.Parent = game.Workspace

        cornClone:SetPrimaryPartCFrame(CFrame.new(xPos,yPos - 1,zPos))

        cornClone:SetPrimaryPartCFrame(CFrame.new(cornClone.PrimaryPart.Position) * CFrame.Angles(0, math.random(100), math.rad(-90))) 

    end
end
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.

local partSize = part.Size

local X_max = partSize.X/2
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.

local partCFrame = part.CFrame

local lookVector = partCFrame.lookVector
local rightVector = partCFrame.rightVector

local randomX = lookVector * math.random(-X_max, X_max)
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.

local newPosition = part.Position + randomX + randomZ

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

Ad

Answer this question