Introduction to Python Scripting in Maya – Part 3: Creating a Scripted Animation

In this part, we’ll introduce how to create keyframes in a Python script. We’ll also cover how to filter for specific object types in the user’s selection, and how to write a simple function. The end result of this part will be a shelf script which rotates the currently selected transform nodes 360 degrees around their local Y axis. Open a new Python tab, and identify the script as Import the maya.cmds module. Similarly to the scripts in Part 2, we’ll use the “ls” command to obtain the user’s current selection. We won’t be concerned with the ordering of the user’s selection, so we can simply use the selection flag instead of orderedSelection. In this case, we’ll want to filter our selection for transform nodes, since these nodes contain the rotation attribute. To get an idea of an object’s type, let’s iterate over the selected objects with the following for-loop. Call cmds.objectType() with the object’s name, and print the result. While holding CTRL, select the instance group, the sphere’s transform node, and the sphere’s shape node. In the Script Editor’s output, you’ll notice the type of each selected object. We’re interested in keying the rotation attribute of ‘transform’ objects. To apply this filter to our selection list, add the type=’transform’ flag to the ls command, and run the script to test it on the current selection. Notice that only the transform objects appear in the output, and that the shape node is excluded from the selection. Comment the objectType command and the following print statements, since we’ve now determined how to narrow our selection. We want our script to overwrite any existing animations assigned to the rotateY attribute, and replace it with a constant rotation from 0 to 360 in the Time Slider’s range. To do this manually, select an object in the scene, and go to “Edit>Keys>Delete Keys>Option Box”. Select the “Time Slider” radio button, and press “Delete Keys”. Note that the resulting MEL command is cutKey. To automate this task in our script, we’ll need the start and end times of the time slider. The start time is accessed by calling cmds.playbackOptions with the query and minTime flags set to True. The end time is obtained with the maxTime flag set to True. Next, call the cutKey command with the following flags. The first argument is the name of the object whose keys we want to remove. The time flag is a tuple which defines the start and end time. The attribute flag is the name of the animated attribute, in this case: rotateY for the transform node’s Y axis rotation. Next, call the “setKeyframe” command. The first argument is the name of the object whose key we want to add. The time flag determines the frame on which the key is set. The attribute is the name of the target attribute we want to animate. The value flag determines the key’s value at the given time. We’ll key the value of 0 at the start time. We’ll also key the value of 360 at the end time. Set the Time Slider from frame 1 to 132. Select the instance group, and run the script. When you press play, the whole group rotates, and each hexagon maintains its aim towards the central sphere. In the Graph Editor, note that the key’s tangents are smoothed, which accelerates and decelerates the speed of rotation. We want to convert these smooth tangents to linear tangents, to maintain a constant rate of rotation as the animation loops. When we press play, the group rotates at a constant rate about its y axis. To set linear tangents in our script, first use the selectKey command to select the attribute’s keys in a specific time range. Then, use the keyTangent command to set the selected key’s incoming and outgoing tangent types to ‘linear’. Run the script to overwrite the previous rotation animation. Notice that the instance group now rotates uniformly around the sphere. To make our script more practical in a general-purpose setting, let’s convert the keyframe creation code into a function. Below the import statement, use the “def” Python keyword to define the keyFullRotation function along with the following parameters. The lower-case “p” prefix is a simple programming guideline to identify the variables declared in the function’s parameters. Cut the block of code between cmds.cutKey() and cmds.keyTangent(), and paste it with one level of indentation below the keyFullRotation function declaration. Replace the objectName variable among these lines with pObjectName. Replace the instances of “startTime” with pStartTime, and the instances of “endTime” with pEndTime. Replace the instances of “rotateY’ with pTargetAttribute. Add a call to our custom keyFullRotation function in the for-loop where we had previously cut the keyframing code. Save the script to your shelf as keyRot You can also save this script to your file system as keyRotation In the next part, we’ll cover how to create an interface to let the user specify which values will be passed to the keyFullRotation function.

7 thoughts on “Introduction to Python Scripting in Maya – Part 3: Creating a Scripted Animation

  1. when I try to execute a script, I got error message but I don't have an idea where the wrong part is…

    import maya.cmds as cmds

    def keyFullRotation( pObjectName, pStartTime, pEndTime, pTargetAttribute):
        cmds.cutKey( pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute)
        cmds.setKeyframe( pObjectName,time=pStartTime, attribute=pTargetAttribute, value=0)    
        cmds.setKeyframe( pObjectName,time=pEndTime, attribute=pTargetAttribute, value=360)    
        cmds.selectKey( pObjectName, time=(pStartTime, pEndTime),attribute=pTargetAttribute,keyframe=True)        
        cmds.keyTangent( inTangentType='linear', outTangentType='linear')    

    selectionList =, type='transform')

    if len(selectionList) >=1:
        #print 'selected items : %s' % (selectionList)
        startTime = cmds.playbackOptions(query=True,minTime=True)
        endTime = cmds.playbackOptions(query=True,maxTime=True)
        for objectName in selectionList:
            #objectTypeResult= cmds.objectType(objectName)
            #print '%s Type %s' % (objectName , objectTypeResult)
            keyFullRotation(objectName, startTime,endTime 'rotateY')

        print'Please select at least one object'

  2. #so for the peeps who dont want to type

    #Introduction to Python Scripting in Maya – Part 3: Creating a Scripted Animation to Python Scripting in Maya – Part 3: Creating a Scripted Animation

    import maya.cmds as cmds
    print '========rotate==========='

    def keyFullRotation (pObjectName, pStartTime,pEndTime,pTargetAttribute):

        cmds.cutKey(pObjectName, time=(pStartTime,pEndTime),attribute=pTargetAttribute)
        cmds.setKeyframe(pObjectName, time=pStartTime,attribute=pTargetAttribute, value=0)
        cmds.setKeyframe(pObjectName, time=pEndTime,attribute=pTargetAttribute, value=360)

        #from smooth to linear tangents
        cmds.selectKey(pObjectName, time=(pStartTime,pEndTime),attribute=pTargetAttribute)
        cmds.keyTangent(inTangentType='linear', outTangentType = 'linear')

    selectionlist = =True)

    if len(selectionlist) >= 1:

        #ask current timeslider start and end
        startTime     = cmds.playbackOptions (query=1,minTime=1)
        endTime     = cmds.playbackOptions (query=1,maxTime=1)
    #    print 'Selected items %s' %(selectionlist)

        for objectName in selectionlist:
            #objectTypeResult = cmds.objectType(objectName)
            #print '%s type %s' %(objectName ,objectTypeResult )
            keyFullRotation(objectName, startTime,endTime,'rotateY')

    else :
        print 'you have no selection nitwit'

  3. When I run this script, it creates an animation alright, but the objects rotate in their local Y axis, and not the world Y axis. How do I correct this?

    I have made sure the code is correct.

  4. Hello,

    I have run the keyRotation script and it only rotates one of the instanced cyclinder's in its own local y-axis. Any help in this issue would be greatly appreciated. I have recreated the entire scene and deleted all keys, but continue to have this issue.


  5. Thanks for this but the Sphere's shape node doesn't appear in my outliner (Maya 2017), just the transform node is visible.

Leave a Reply

Your email address will not be published. Required fields are marked *