Mel

Getting Started with Loops


main index



Introduction

The purpose of this tutorial is to get you started with Mel scripting. We will begin with the use of a single "for" loop to create a column of spheres - listing 1, figure 1.

Listing 1 - grid1d.mel


select -all;
delete;
  
for($x = 0; $x < 8; $x++) {
    sphere -r 0.25;
    move 0 (0.5 * $x) 0;
    }


Figure 1



Listing 2 demonstrates how nested loops can be used to produce a 2D array of spheres..

Listing 2 - grid2d.mel


select -all;
delete;
  
for($x = 0; $x < 8; $x++) {
    for($y = 0; $y < 8; $y++) {
        sphere -r 0.25;
        move (0.5 * $x) (0.5 * $y) 0;
        }
    }


Figure 2



By nesting a third loop inside a 3D array of spheres can be produced - shown in figure 3.



Figure 3



Holes / Voids

Listing 3 demonstrates the use of a "if" test to determine when spheres should not be inserted.


Listing 3 - holes2d.mel


select -all;
delete;
  
for($x = 0; $x < 8; $x++) {
   for($y = 0; $y < 8; $y++) {
      if($x > 2 && $x < 5 || 
         $y > 2 && $y < 5) 
           {
           // leave a "hole"
           }
       else
           {
           sphere -r 0.25;
           move (0.5 * $x) 
                (0.5 * $y) 
                 0;
           }
       }
   }


Figure 4



Changing the "AND" (&&) and the "OR" (||) of the test produces very different gaps within the 2D array of spheres. Moving the code that inserts the spheres into the "empty" block produces the "reverse" of the pattern. For example,


if($x > 2 && $x < 5 || 
   $y > 2 && $y < 5) 
    {
    sphere -r 0.25;
    move (0.5 * $x) 
         (0.5 * $y) 
          0;
    }
else
    {
    // leave a "hole"
    }


Figure 5


In listing 4 the loops have been changed so that a sequence of poly cubes are inserted into the scene in 'Z' (depth) order. The inner 'Y' loop has also been modified so as to produce the wedge effect shown in figure 6.


Listing 4 - wedge.mel


select -all;
delete;
  
for($z = 0; $z < 8; $z++) {
   for($y = 0; $y < 8 - $z; $y++) {
      for($x = 0; $x < 8; $x++) {
         if($x > 2 && $x < 5 || 
            $y > 2 && $y < 5) 
            {
            polyCube -w 0.35 
                     -h 0.35 
                     -d 0.35;
            move (0.5 * $x) 
                 (0.5 * $y) 
                 (0.5 * $z);
            }
         else
            /* leave a "hole" */ ;
         }
      }
   }


Figure 6




© 2002- Malcolm Kesson. All rights reserved.