Python Tools - Session 4A
Helix Pattern with FOR Loops
January 28, 2020
Session Navigation
Overview
This session explores function definitions and mathematical functions to create visually striking 3D patterns. By combining math.sin() for Z-axis oscillation with incremental Y positioning and world-space pivot rotation, you'll generate a helix of 500 spheres spiraling around the scene origin. The session also covers variable scope and how parameters pass data into functions.
Key Concepts
- Function definitions — using
defto create reusable functions with parameters - math.sin() — generating oscillating values between -1 and 1 for wave-like motion
- World-space pivots — setting the pivot to the origin with
pm.xform()to rotate objects around a central point - Iteration scaling — dividing or multiplying the loop counter to control spacing and rotation speed
- Variable scope — understanding that variables defined inside a function are local to that function
Code
This script defines a function that creates a sphere, positions it using sine-wave oscillation, and rotates it around the world origin to form a helix.
"""
#############################################################################
filename session_4a_code_commented.py
author Matt Osbond
course CS115
Brief Description:
Session 4A - Tuesday Jan 28th
Using a FOR loop and some math to create a helix effect
#############################################################################
"""
import pymel.core as pm
import math
def create_ball(iter, size):
"""This is a function DEFINITION, as indicated by the "def" keyword.
The parentheses that follow the name of the function are called the parameters.
These are variables that will be defined elsewhere, where the function is called from.
"""
# Create a ball, remembering to return the first element (element 0) of the list returned by "polySphere"
ball = pm.polySphere(radius=size/2)[0]
# Here we begin to make the position in Z vary with each iteration, by using the "sin" math function
# This returns a value that will fluctuate between 1 and -1
# As this is such a small variation in the Maya scene, we multiply by 10 to exaggerate the effect
z_pos = math.sin(iter) * 10
# Each step, we want to move the ball higher up in Y
# But, if we add 1 each time (use the iteration of the FOR loop) then it will go up too fast
# and the balls will be too spread out
# So we opt to divide this by 10
y_pos = iter/10
# Move the ball to the new location
pm.move(ball, [0, y_pos, z_pos])
# We now want to rotate the ball around the scene origin
# To do this, set the world space pivot to [0,0,0]
pm.xform(worldSpace=True, piv=[0, 0, 0])
# Calculate the y rotation, by first assigning it to be iter, then choosing to
# speed it up or slow it down (increasing the multiplier will make it rotate faster)
y_rot = iter * 1.5
# Rotate around Y axis
pm.rotate([0, y_rot, 0])
# Create 500 balls
for i in xrange(0, 500):
create_ball(i, 5)