First Python Script in Maya

______________ update _____________
I rewrote the script with PyMel after reading the Maya Python book. It’s now better structured and organized than the original, although some functions remain procedural…View it on Github.
__________ end of update __________

Last weekend I got my very first python script working in Maya. :) It can be used to randomly disperse one object onto multiple target surfaces.

result

I put the complete script on Github.
First import necessary modules.

Then create a class called Disperser. In the initialize function I made up a simple GUI as shown below.

GUI

And the corresponding code:

I want the source text field to display the selected object name when I hit the “Select” button, assign it to sourceObj if only one object is selected:

To handle multiple targets and pave the road for the random disperse later, I created three lists:
targetObjs – list of selected target objects
targetVertNumList – list of selected target objects’ number of vertices, this is to make later random disperse easier
vertIndexList – list of integers from 0 to the total number of vertices of all targets

Then we get to the Disperse function, which first detects if the selection is valid:

Extract the info from input:

After that, I generated a list(which has copyNum elements) to store unique values randomly chosen from vertIndexList. This way we evaluate random function beforehand, otherwise we’ll have to write the random function inside the for loop later. That is a trade-off between memory use and CPU overhead. In this case I chose faster speed, nonetheless it doesn’t matter that much just because we probably won’t need to make hundreds of thousands of copies.

Next we make copies of the source object:

Decide which target shall this new object go to. For example, if we have three targets, with 30, 20, and 40 vertices relatively, targetVertNumList would become [30, 20, 40], elements in randVertIndexList would range from 0 to 89. Suppose we get value of 34 from randVertIndexList[i], we compare it with vertSum, and find out it falls on the second target.

Remaining is to apply scale and rotation based on input:

Lastly, I removed the normal constraint if rotation mode is set to “Align with target”. If we wanna adjust new object’s position along the targets however, this could be commented out.

Please don’t hesitate to point out any bug or error if you spot one – which would be more than welcome, via comments or email or Github.

One Comment

Leave a Reply