View Single Post
# 5 20-10-2011 , 02:21 AM
ctbram's Avatar
Moderator
Join Date: Jan 2004
Location: Michigan, USA
Posts: 2,998
Okay I keep wanting to learn mel so this is as good a way as any.

I listed some pseudo above for an algorithm to randomly swap the positions and orientations of pairs of objects. Below is the code I came up with. It takes the current selection of objects and each time it is run two objects positions are swapped.

Keep in mind I have never spent much time writing mel and every thing in this script I learned in about 10 minutes of googling things on the net so I am pretty sure anyone that really knows the proper way to write mel will realize it is probably total crap so feel free to make improvements but please do not beat me up to much for the effort.



string $select[] = `ls -sl`; // get current selection
int $l = size($select); // get the number of objects in the selection
int $i;
string $temp;

/*
pick a random index from 0 to $l-1
if it's not the index of the last item
swap the items at $i and $l-1
*/
$i = rand(0,$l-1);
if ($i != $l-1)
{
swap($i, $l-1, $select);
}

/*
pick a random index from 0 to $l-2
if it's not the index of the second to last item
swap the items at $i and $l-2
*/
$i = rand(0,$l-2);
if ($i != $l-2)
{
swap($i, $l-2, $select);
}

print $select; // print the selection array, the last two items will be swapped
swapPos($select[$l-1], $select[$l-2]);
print ".....................";


// procedure to swap two objects in the array $select[]
proc swap(int $i1, int $i2, string $select[])
{
string $temp;
$temp = $select[$i2];
$select[$i2] = $select[$i1];
$select[$i1] = $temp;
}

// procedure to swap the position and orientation of two objects
proc swapPos(string $obj1, string $obj2)
{
float $tx,$ty,$tz;
float $rx,$ry,$rz;

$tx = `getAttr($obj1 + ".translateX")`;
$ty = `getAttr($obj1 + ".translateY")`;
$tz = `getAttr($obj1 + ".translateZ")`;
$rx = `getAttr($obj1 + ".rotateX")`;
$ry = `getAttr($obj1 + ".rotateY")`;
$rz = `getAttr($obj1 + ".rotateZ")`;

setAttr($obj1 + ".translateX") `getAttr($obj2 + ".translateX")`;
setAttr($obj1 + ".translateY") `getAttr($obj2 + ".translateY")`;
setAttr($obj1 + ".translateZ") `getAttr($obj2 + ".translateZ")`;
setAttr($obj1 + ".rotateX") `getAttr($obj2 + ".rotateX")`;
setAttr($obj1 + ".rotateY") `getAttr($obj2 + ".rotateY")`;
setAttr($obj1 + ".rotateZ") `getAttr($obj2 + ".rotateZ")`;

setAttr($obj2 + ".translateX") $tx;
setAttr($obj2 + ".translateY") $ty;
setAttr($obj2 + ".translateZ") $tz;
setAttr($obj2 + ".rotateX") $ry;
setAttr($obj2 + ".rotateY") $ry;
setAttr($obj2 + ".rotateZ") $rz;
}

and here is a short video showing how it works...

how to mel scripte to randomly swap obj positions - YouTube


"If I have seen further it is by standing on the shoulders of giants." Sir Isaac Newton, 1675

Last edited by ctbram; 20-10-2011 at 02:36 AM.