Santosh Kumar
Santosh Kumar

Reputation: 27875

How to set random locations to poly objects in Maya with Python?

So here is my code:

import maya.cmds as mc
import random

x = random.random() * 10
y = random.random() * 10
z = random.random() * 10

for i in range(5):
    mycube = mc.polyCube(h=3, w=3, d=3, n="Object#")
    mc.move(x, y, z, mycube)

Things should be clear what I am trying to do. I'm creating 5 polyCube's and setting them random location in 3 dimensional world. My version of Maya is 2009 if it helps.

Upvotes: 0

Views: 3658

Answers (1)

Santosh Kumar
Santosh Kumar

Reputation: 27875

Move the x, y and z lines inside the for loop. Thanks Blender for pointing it out.

Another unusual thing you might notice when running this updated code is that cubes that are created are on a certain section on the viewport. That is because random.random is not creating values in negatives, so value is not going in negative in either of the axis x, y and z.

When we use random.random

To overcome this problem you can replace the codes in x y and z definition lines:

x = random.uniform(-10.0, 10.0)
y = random.uniform(-10.0, 10.0)
z = random.uniform(-10.0, 10.0)

When we use random.uniform

Now it works as expected.

Upvotes: 2

Related Questions