# How do I make math.random work with positions?

This picture above is literally my nightmare. I can’t figure out a way to make the script choose between one of those guns when I press F. How do I fix this?

Thanks.
(yes i did know i can do code blocks but i took a picture)

Well, use a dictionary maybe?

``````local guns1p = launcher.Gun1.CFrame
local guns2p = launcher.Gun2.CFrame
local guns3p = launcher.Gun3.CFrame
local dictionary = {
1 = guns1p;
2 = guns2p;
3 = guns3p;
}
-- The rest of your code here...
rocket.CFrame = dictionary[tostring(math.random(1, 3))]
``````
1 Like

What? It looks like you messed something up.

Here’s a way to do things:

``````-- order your positions like this
local guns1p = launcher.Gun1.CFrame
local guns2p = launcher.Gun2.CFrame
local guns3p = launcher.Gun3.CFrame
local randomPositions = {guns1p, guns2p, guns3p}

-- and then for actual random picking, do this:
rocket.CFrame = randomPositions[math.random(1,#randomPositions)]``````

``````["1"] = guns1p;
["2"] = guns2p;
["3"] = guns3p;
``````

Forgot you can’t write normal numbers on dictionaries.

you can also do [1] instead of using it as a string

2 Likes

I see. I’ll try that right now.

Oh? I didn’t know that, I was sure you could only use strings. Thanks for letting me know.

the code i sent is a bit cleaner and reduces the amount of letters you need to type – using
[1] = this, [2] = that can be beaten by a simple table with {position1, position2},

basically what i mean is theres no need to over complicate things when it can be made simple

1 Like

Uh… the equals disagreeing or?

both are sufficient i guess. i think the better option for the posters use case is to simply have an array and math.random it to avoid over complicating things (i.e. using a dictionary when it isn’t needed)

You put two `rocket.CFrame`. One is enough. You did:

``````rocket.CFrame = rocket.CFrame = dictionary[tostring(math.random(1, 3))]
``````

But it’s supposed to be:

``````rocket.CFrame = dictionary[tostring(math.random(1, 3))];
``````

Did not notice that. Sorry.

1 Like

Now they aren’t moving…

``````local X, Y, Z = math.random(1, 1000), math.random(1, 1000), math.random(1, 1000) -- feel free to adjust
Part.Position = Vector3.new(X, Y, Z)``````

Using your idea, I’ve decided to revamp my entire missile launcher, and used one barrel. Good thing is that now the missile is teleporting to the CFrame of the barrel!

That’s awesome! I’m glad you learned something new.