maya -tutorial (expressions)

Upload: chay-garcia

Post on 18-Oct-2015

126 views

Category:

Documents


5 download

DESCRIPTION

Maya -Tutorial (Expressions)

TRANSCRIPT

  • 5/28/2018 Maya -Tutorial (Expressions)

    1/274

    Expressions

  • 5/28/2018 Maya -Tutorial (Expressions)

    2/274

  • 5/28/2018 Maya -Tutorial (Expressions)

    3/274

    Using Maya: Hypergraph, Sets & Expressions 3

    Expressions

    3 Introducing Expressions 11

    About expressions 12

    Where you create expressions 13

    4 Quick Start 15

    Preparing for the examples 15

    Creating a simple expression 17

    Controlling multiple attributes of an object 23

    Controlling attributes in two objects 28

    Controlling attributes conditionally 32

    Notes on the predefined time variable 43

    5 Expression Syntax 45

    Expressions and MEL 46

    Elements of an expression 47Attributes 49

    Static attributes 49

    Dynamic attributes 49

    Custom attributes 50

    Attribute names 51

    Data types of attributes 51

    Assigning a value to an attribute 55

    Variables 56

    Data types of variables 57

    Predefined variables 57

    Custom variables 59

  • 5/28/2018 Maya -Tutorial (Expressions)

    4/274

    4 Using Maya: Hypergraph, Sets & Expressions

    ExpressionsContents

    Constants 62Arithmetic, logic, and relational operators 63

    Arithmetic operators 63

    Relational operators 65

    Logical operators 67

    Operator precedence 68

    Conditional statements 69

    if statements 69

    if-else statements 70

    else if statements 71

    General syntax rules 73

    Comments in expressions 75

    Programming features 75

    Notes for C programmers 75

    Expression language keywords 76

    Flow control statements 77

    Flow control errors 88

    String usage 90

    Shortcut assignment operators 91

    Shortcut increment and decrement operators 92

    Arrays 93

    Boolean symbolic constants 95

    Common expression errors 95

    Error message format 95

    Common error messages 97

    6 Editing Expressions 99

    Finding expressions 99

    Finding by expression name 100

    Finding by selected object 101

  • 5/28/2018 Maya -Tutorial (Expressions)

    5/274

    Using Maya: Hypergraph, Sets & Expressions 5

    ExpressionsContents

    Finding by item type 102Using the Selection list 103

    Filtering attributes from the Selection list 104

    Editing an expression in the text field 105

    Deleting and copying text 105

    Clearing the expression text field 106

    Reloading an expressions previous contents 106

    Editing an expression with a text editor 106

    Using an editor listed in the Editor menu 107

    Using an editor not listed in the Editor menu 109

    Changing an editors operation settings 110

    Selecting an editor for default startup 110

    Creating a new expression 111

    Deleting an expression 112

    Using attribute names in expressions 112

    Using attribute name abbreviations 113

    Omitting an object name in expressions 115

    Combining the abbreviation techniques 116

    7 Beyond the Basics 117

    How often an expression executes 118

    Using custom attributes in expressions 118

    Displaying attribute and variable contents 123

    Reproducing randomness 123

    Speeding expression execution 127

    Reducing redundant expression execution 130

    Removing an attribute from an expression 131

    Disconnecting an attribute 132

    Displaying disconnected attributes in expressions 132

    Connecting an attribute to a symbolic placeholder 135

  • 5/28/2018 Maya -Tutorial (Expressions)

    6/274

    6 Using Maya: Hypergraph, Sets & Expressions

    ExpressionsContents

    Renaming an object 136Executing MEL commands in an expression 137

    Understanding path names 140

    Understanding unexpected attribute values 141

    Values after rewinding 141

    Increment operations 142

    Data type conversions 143

    8 Particle Expressions 147

    Understanding particle expressions 148

    Understanding creation expression execution 149

    Setting the dynamics start frame 149

    Setting attributes for initial state usage 150

    Writing creation expressions 150

    Understanding runtime expression execution 152

    Writing runtime expressions 153

    Working with particle attributes 159

    Adding dynamic attributes 159

    Understanding per particle and per object attributes 160Understanding initial state attributes 162

    Example of assigning to a dynamic per particle attribute 164

    Example of assigning to a dynamic per object attribute 167

    Assigning to a custom attribute 169

    Assigning to a particle array attribute of different length 172

    Using creation expression values in a runtime expression 174

    Working with position, velocity, and acceleration 175

    Working with color 178

    Working with emitted particles 183

    Working with collisions 183

    Working with specific particles 189

  • 5/28/2018 Maya -Tutorial (Expressions)

    7/274

    Using Maya: Hypergraph, Sets & Expressions 7

    ExpressionsContents

    Assigning to vectors and vector arrays 193List of particle shape attributes 196

    9 Functions 203

    Understanding functions 205

    Function syntax 206

    Data types 208

    Understanding function examples in this chapter 208

    Limit functions 209

    abs 209

    ceil 210

    floor 210

    clamp 211

    min 212

    max 212

    sign 212

    trunc 213

    Exponential functions 214

    exp 214log 214

    log10 214

    pow 215

    sqrt 215

    Trigonometric functions 216

    cos 216

    cosd 218

    sin 219

    sind 224

    tan 224

    tand 225

  • 5/28/2018 Maya -Tutorial (Expressions)

    8/274

    8 Using Maya: Hypergraph, Sets & Expressions

    ExpressionsContents

    acos 225acosd 226

    asin 226

    asind 226

    atan 227

    atand 227

    atan2 227

    atan2d 228

    hypot 228

    Vector functions 229

    angle 229

    cross 230

    dot 231

    mag 231

    rot 232

    unit 233

    Conversion functions 234

    deg_to_rad 234

    rad_to_deg 234

    hsv_to_rgb 235

    rgb_to_hsv 235

    Array functions 236

    clear 236

    size 237

    sort 237

    Random number functions 239

    gauss 239

    noise 241

    dnoise 242

    rand 243

    sphrand 244

  • 5/28/2018 Maya -Tutorial (Expressions)

    9/274

    Using Maya: Hypergraph, Sets & Expressions 9

    ExpressionsContents

    seed 246Curve functions 249

    linstep 249

    smoothstep 252

    hermite 254

    General commands 259

    eval 259

    print 261

    system 263

    Other functions and commands 264

  • 5/28/2018 Maya -Tutorial (Expressions)

    10/274

    10 Using Maya: Hypergraph, Sets & Expressions

    ExpressionsContents

  • 5/28/2018 Maya -Tutorial (Expressions)

    11/274

    Using Maya: Hypergraph, Sets & Expressions 11

    Expr

    essions

    3 Introducing ExpressionsExpressions are instructions you type to control an object attribute over time.An attribute is a characteristic of an object, for instance, X scale, Y translate,visibility, and so on.

    Though you can create an expression to animate attributes for any purpose,theyre ideal for attributes that change incrementally, randomly, orrhythmically over time.

    Expressions are also useful for linking attributes between different objectswhere a change in one attribute alters the behavior of the other. For instance,you can make the rotation of a tire dependent on the forward or backwardmovement of a car.

    This chapter has the following topics:

    About expressions on page 12

    Where you create expressions on page 13

    An expression gives themanta rays wings a fluid,rhythmic motion.

    Eric Saindon

  • 5/28/2018 Maya -Tutorial (Expressions)

    12/274

    12 Using Maya: Hypergraph, Sets & Expressions

    Introducing Expressions

    About expressions

    About expressionsExpressions offer an alternative to difficult keyframing tasks. In keyframing,you set the values of attributes at selected keyframes in the animation, andMaya interpolates the action between the keyframes. With expressions, youwrite a formula, then Maya performs the action as the animation plays.

    Expressions are often as simple as a few words or lines. In the followingexample expressions, note the variation in length and detail (rather thantheir purpose).

    Example

    Ball.translateX = Cube.translateX + 4;

    Example

    if (frame == 1)

    Cone.scaleY = 1;

    else

    {

    Cone.scaleY = (0.25 + sin(time)) * 3;

    print(Cone.scaleY + "\n");

    }

    Though many expressions look like math or a programming language, youdont need to be a mathematician or programmer to learn how to use them.If youre fond of programming, expressions offer unlimited animation

    techniques that would challenge the skill of keyframing experts.

    You can use an expression to animate any keyable, unlocked object attributefor any frame range. You can also use an expression to control per particle orper object attributes. Per particle attributes control each particle of an objectindividually. Per object attributes control all particles of an objectcollectively.

    You cannot apply an expression to an attribute already animated with any ofthese techniques:

    keys

    set driven key

    constraint motion path

  • 5/28/2018 Maya -Tutorial (Expressions)

    13/274

    Using Maya: Hypergraph, Sets & Expressions 13

    Introducing Expressions

    Where you create expressions

    Expr

    essions

    another expression

    any other direct connection

    If you do so, youll see an error message in the Script Editor and theCommand Lines response area.

    Though you cant control a single attribute with two of the precedingtechniques, you can control one attribute with keyframes, another with anexpression, another with a constraint, and so on.

    Also, you can use a single expression to assign values to several attributes ofone or more objects.

    Where you create expressionsYou create and edit an expression in the Expression Editor. There are severalways to start the Expression Editor:

    From the main menu bar or Hotbox, chooseWindowExpression Editor.

    From the Channel Box, click the right mouse button in an attribute text fieldand selectExpressions.

    From the Attribute Editor, click the right mouse button in an attribute textfield and selectCreate New Expression,Edit Expression, orExpressionEditor.

    You cannot start the Expression Editor from every attribute text field in the

    Channel Box and Attribute Editor. UseWindowExpression Editorifnecessary.

  • 5/28/2018 Maya -Tutorial (Expressions)

    14/274

    14 Using Maya: Hypergraph, Sets & Expressions

    Introducing Expressions

    Where you create expressions

    The Expression Editor follows:

    The expression text field expands as you type text, so you can writeexpressions of unlimited length. You can also edit expressions with a texteditor such as jot by selecting it from the Editorpull-down menu above thetext field.

    Expression text field

  • 5/28/2018 Maya -Tutorial (Expressions)

    15/274

    Using Maya: Hypergraph, Sets & Expressions 15

    Expr

    essions

    4 Quick StartThe easiest way to learn about expressions is to work through examples. Forthis reason, we provide the following introductory lessons. Expressions thatcontrol particle attributes are more complex than for other objects. Forexamples, see Chapter 8, Particle Expressions.

    In this chapter, youll learn about the following topics:

    Creating a simple expression on page 17

    Controlling multiple attributes of an object on page 23

    Controlling attributes in two objects on page 28

    Controlling attributes conditionally on page 32

    Notes on the predefined time variable on page 43

    Preparing for the examplesA few preparatory steps will simplify your understanding of the examples inthis chapter. Before starting the examples, do these steps:

    To prepare for the examples:

    1 SelectOptionsGeneral Preferences.

    You can use an expression to linkattributes in different objectssoa change in one attribute altersthe behavior of the other.

  • 5/28/2018 Maya -Tutorial (Expressions)

    16/274

    16 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Preparing for the examples

    The General Preferences window appears.

    Drag either side of the General Preferences window to expand its width. Youmust do this to display theUnitstab in the window.

    2 Click theUnitstab.

    3 In theUnitstab, make sureTimeis set toFilm (24 fps).

    This makes your animation play at the default rate of 24 frames per second.

    4 In the General Preferences window, choose theAnimationtab.

    5 Enter 0 for the starting frame of theTime Sliderand theRange Slider, andenter 300 for the ending frame of theTime SliderandRange Slider.

    Specifying a range of 300 frames gives ample time to see the effects youllcreate in the examples.

    6 In the General Preferences window, clickSaveandClose.

    7 At the top edge of the workspace, selectShadingSmooth Shade All todisplay all objects you create in the scene with smooth shading.

    This will enhance the look of the objects you create in the examples.8 From the menu bar, chooseWindowExpression Editorto display the

    Expression Editor.

    Important

    For the lessons to work correctly, you must enter 0 for the starting frame oftheTime SliderandRange Slider. Press your keyboards Enter key aftereach entry. Rewind the animation to frame 0. After doing the lessons, readNotes on the predefined time variable on page 43 for details on why thelessons require the starting frame to be 0.

  • 5/28/2018 Maya -Tutorial (Expressions)

    17/274

    Using Maya: Hypergraph, Sets & Expressions 17

    Quick Start

    Creating a simple expression

    Expr

    essions

    9 Make sure these default Expression Editor menu options are selected:

    Select FilterBy Object/Attribute Name

    Object FilterSelected Objects

    Attribute FilterAll

    Finding expressions in Chapter 6 gives details on these options.

    Creating a simple expressionThe following steps show how to control an attribute of a single object. Anattribute is a characteristic of an object, for example, X scale, Y scale,

    X rotation, and so on.

    In this example, youll learn how to stretch a sphere along its Y-axis bycontrolling its scaleY attribute as the animation plays.

    To prepare the scene:

    1 From the Modeling menu, choosePrimitivesCreate NURBSSphere.

    This creates a NURBS sphere with an X scale, Y scale, and Z scale of 1.

    2 In the Channel Box or elsewhere, name the sphere Ball.

    3 Select DisplayNURBS SmoothnessFineto set Balls display smoothnessto fine resolution.

    Maya displays the object with extra polygons to make it look smoother inthe workspace. This doesnt affect the underlying models geometry. It altersonly its display.

    4 Rewind the animation to frame 0.

  • 5/28/2018 Maya -Tutorial (Expressions)

    18/274

    18 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Creating a simple expression

    To create the expression:

    1 Make sure Ball is selected.

    2 ChooseWindowExpression Editor to display the Expression Editor.

    The selected objects name, Ball, is highlighted in the Objects list of theExpression Editor.

    3 Enter ScaleBallHeight in theExpression Namebox.

    Entering an expression name lets you find the expression easily in a laterwork session if you decide to alter it.

    Use alphabetical and numerical characters for expression names. If you usespace characters or special characters such as a hyphen (-), Maya deletes

    them or replaces them with an underscore character (_) after you finishcreating the expression.

    4 Notice the Attributes list.

    It displays Balls keyable, unlocked attributesthe attributes youll mostlikely want to animate with an expression. Use the scroll bar to see the entirelist.

    5 Enter this expression in the expression text field:

    Enter the expression with the same upper and lowercase spelling shown.Entries in the expression field are type case sensitive.

    The semicolon (;) signifies the end of the expression statement. Eachstatement in an expression must end with a semicolon. The only exception iswhen the expression has a single statement.

    An error message appears in the Script Editor and Command Linesresponse area if the expression has incorrect syntax or typing mistakes.

    Edit text the same way you edit other text fields in Maya.

    Ball.scaleY = time + 1;

  • 5/28/2018 Maya -Tutorial (Expressions)

    19/274

    Using Maya: Hypergraph, Sets & Expressions 19

    Quick Start

    Creating a simple expression

    Expr

    essions

    6 ClickCreate to compile the expression.

    Compiling the expression checks it for syntax errors and converts it to aform Maya can execute when you rewind or play the animation. Clickingthis button also executes the expression for the current frame.

    The expression sets Balls scaleY attribute to the value of time + 1. Ball.scaleYis the full name of the attribute. A period separates the name of the objectand attribute. You must spell them with uppercase and lowercase letters asthey appear in the Expression Editors Objects and Attributes lists. SeeUsing attribute names in expressions in Chapter 6 for more details.

    The word timeis a predefined variable in Maya that updates as an animationplays. It contains the elapsed number of seconds from the first frame to the

    current frame. The value increases with the increasing frame number.At the default animation playback rate of 24 frames per second, time hasthese values, rounded to four decimal places:

    If you ever need to change the playback rate, you can do so by choosingOptionsGeneral Preferences. Expand the General Preferences window,display the Units folder, and choose the desired rate from theTimemenu.

    Regardless of what animation playback rate you choose, you can find thetime elapsed in the animation at any frame with this formula:

    For example, if the frame rate is 24 frames/second and the animation is atframe 1, the elapsed time is 1 divided by 24, or 0.0417. At frame 6, theelapsed time is 6 divided by 24, which equals 0.25.

    Frame Time (seconds)

    0 0

    1 0.0417

    2 0.0833

    3 0.125

    24 1.0

    240 10.0

    time frame

    rate---------------=

  • 5/28/2018 Maya -Tutorial (Expressions)

    20/274

    20 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Creating a simple expression

    If the frame rate is 30 frames/second and the animation is at frame 1, theelapsed time is 1 divided by 30, which equals 0.0333. At frame 6, elapsedtime is 6 divided by 30, which equals 0.2.

    To see the result of the expression:

    1 Rewind and play the animation.

    Balls scaleY attribute increases as the time increases:

    Maya executes the expression each frame. This causes the object size to scalealong its Y-axis, stretching its height during playback.

    The scaling is smooth because the geometry stretches in synch with the smalltime increments of the animation playback.

    Frame Time (seconds) Ball.scaleY (time + 1)

    0 0 1

    1 0.0417 1.0417

    2 0.0833 1.0833

    3 0.125 1.125

    24 1.0 2.0

    240 10.0 11.0

  • 5/28/2018 Maya -Tutorial (Expressions)

    21/274

    Using Maya: Hypergraph, Sets & Expressions 21

    Quick Start

    Creating a simple expression

    Expr

    essions

    2 Stop and rewind the animation.

    Rewinding the animation returns Ball to its original shape. This occursbecause the expression executes with time equal to 0. The value of time + 1 is1, the original scaleY value of Ball.

    3 Play the animation.

    This repeats the increasing scale.

    4 Stop and rewind the animation.

    5 Close the Expression Editor window.

    This complete the steps to creating an expression.

    To further your understanding of expressions, weve included the followingsteps to show how to edit the expression you just completed.

    To edit the expression:

    Suppose you decide that Ball scales too quickly as the animation plays. Youcan change the expression to see how the animation looks when you scaleBall half as fast.

    1 ChooseWindowExpression Editor to display the Expression Editor again.

    You can find the expression you created earlier by:

    remembering the name of the expression

    remembering the name of the object and attribute you controlled with theexpression

    examining each expression in the scene thats controlled by an expression

    In this example, youll find the expression ScaleBallHeight by its name. SeeChapter 6, Editing Expressions for details on the other methods.

    2 ChooseSelect FilterBy Expression Name.

    3 ClickScaleBallHeightin the Expressions list.

    The expression appears in the expression text field.

  • 5/28/2018 Maya -Tutorial (Expressions)

    22/274

    22 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Creating a simple expression

    4 Change the previous expression to this:

    Ball.scaleY = time/2 + 1;

    Use the same editing techniques you use with other text fields in Maya.

    By dividing time by 2, youll make the Y scaling increase half as fast as withthe previous version of the expression.

    5 ClickEditto compile the modified expression.

    Compiling the expression checks it for syntax errors and converts it to aform Maya can execute when you rewind or play the animation. After beingcompiled, the expression executes for the current frame.

    Clicking theEditbutton does the same action as clicking theCreatebutton.TheCreatebutton exists only for new expressions. TheEditbutton replacestheCreatebutton when you display an existing expression.

    To see the result of the edited expression:

    1 Play the animation.

    Ball scales its Y dimension half as fast as with the previous expressioncontents.

    2 Stop and rewind the animation.

    Feel free to experiment with other values in the expression.

    This concludes the first example. Before starting the next example, delete thescene and create a new scene.

    Summary

    In this lesson, you learned how to:

    name an expression and type it in the expression text field

    Ball.scaleY = time + 1;

  • 5/28/2018 Maya -Tutorial (Expressions)

    23/274

    Using Maya: Hypergraph, Sets & Expressions 23

    Quick Start

    Controlling multiple attributes of an object

    Expr

    essions

    compile an expression to a form Maya can execute

    work with the predefined variable time

    find an expression you previously created

    modify an expression

    Controlling multiple attributes of an objectYou can use a single expression to control two or more attributes of anobject. In the following steps, youll use an expression to increase the X, Y,and Z scale attributes of a sphere as the animation plays.

    To prepare the scene:

    1 From the Modeling menu, choosePrimitivesCreate NURBSSphere.This creates a NURBS sphere with an X scale, Y scale, and Z scale of 1.

    2 In the Channel Box or elsewhere, name the sphere Planet.

    3 SelectDisplayNURBS SmoothnessFineto set the Planets displaysmoothness to fine resolution.

    4 Display the Expression Editor and selectSelect FilterBy Object/AttributeName.

    5 Rewind the animation to frame 0.

    To create the expression:

    1 Select the Planet object.Planet becomes the selected object in the Expression Editor.

    2 In the Expression Editor, enter ScalePlanet in the Expression Namebox.

  • 5/28/2018 Maya -Tutorial (Expressions)

    24/274

    24 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling multiple attributes of an object

    This names the expression so you can find it more easily later.

    3 Enter these statements in the expression text field:

    The expression has three statements. Each statement sets an attribute to thevalue of the predefined variable time.

    4 ClickCreate to compile the expression.

    An error message appears in the Script Editor and Command Linesresponse area if the expression has incorrect syntax.

    Planet disappears because clickingCreate also executes the expression at thecurrent frame after compiling. At frame 0, time is 0, so the value of the

    scaleX, scaleY, and scaleZ attributes becomes 0. Planet has no size, so itdisappears.

    To see the result of the expression:

    1 Play the animation.

    The expression executes each frame, so Planet grows quickly as theanimation plays.

  • 5/28/2018 Maya -Tutorial (Expressions)

    25/274

    Using Maya: Hypergraph, Sets & Expressions 25

    Quick Start

    Controlling multiple attributes of an object

    Expr

    essions

    Because animation playback increases time, the value of Planets scaleX,

    scaleY, and scaleZ attributes increase at the rate of the increasing time.

    The object increases its scale until the last frame of the Time Slider plays.

    2 Stop and rewind the animation.

    The following two series of steps show how to see the same result with othermethods.

    To see the result by linking attribute values:

    1 Change the expression to this:

    Planet.scaleX = time;

    Planet.scaleY = Planet.scaleX;

    Planet.scaleZ = Planet.scaleX;

    2 ClickEdit to compile the expression.

    3 Play the animation.

    The expression works the same as the previous one. The first statement setsPlanet.scaleX to the value of time.

    The second statement sets Planet.scaleY to the value of Planet.scaleX.Because youve set Planet.scaleX to the value of time, Planet.scaleY also hasthe value of time. Youre simply transferring one attributes value to another.

    The third statement also sets Planet.scaleZ to the value of the attributePlanet.scaleX.

  • 5/28/2018 Maya -Tutorial (Expressions)

    26/274

    26 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling multiple attributes of an object

    The advantage of this expression is that if you assign a different value toPlanet.scaleX in the first statement, the second and third statementsautomatically receive the new value. In other words, youve linkedPlanet.scaleY and Planet.scaleZ to the value of Planet.scaleXwhatever itsvalue is.

    4 Stop and rewind the animation.

    5 In the first statement of the expression, divide time by 5 as follows:

    Planet.scaleX = time/5;

    Planet.scaleY = Planet.scaleX;

    Planet.scaleZ = Planet.scaleX;

    6 ClickEdit to compile the expression.

    7 Play the animation.

    Planet increases its scale attributes one-fifth as fast of the previousexpression.

    By assigning the value of Planet.scaleX to Planet.scaleY and Planet.scaleZ,Planet.scaleY and Planet.scaleZ were automatically assigned the value time/5 in the second and third statements.

    8 Stop and rewind the animation.

    You can get the same result using a variable in an expression.

    To see the results using a variable:

    1 Change the expression to this:float $increment;

    $increment = time/5;

    Planet.scaleX = $increment;

    Planet.scaleY = $increment;

    Planet.scaleZ = $increment;

    The expression has the same result as the previous one. The first statementdefines a variable named $increment to be used as storage for the value of atime increment. You define it as a floating point numbera number that canhave a decimal point.

    The second statement assigns $increment the value of time divided by 5. Asthe animation plays and the time increases each frame, the value of$increment increases by the value of time divided by 5. The $incrementtherefore increases in smaller units than time increases.

  • 5/28/2018 Maya -Tutorial (Expressions)

    27/274

    Using Maya: Hypergraph, Sets & Expressions 27

    Quick Start

    Controlling multiple attributes of an object

    Expr

    essions

    The next three statements assign the contents of $increment to the three scaleattributes of Planet. The scale attributes therefore receive the value of timedivided by 5 each frame. This makes the object increase uniformly in scaleslowly as the animation plays.

    2 ClickEdit.

    3 Play the animation.

    The result is the same as with the previous expression

    4 Stop and rewind the animation.

    You can make a change to the variable assignment in the second statementwithout altering the other statements.

    To modify the variable:

    1 Change the expression to this:

    float $increment;

    $increment = time * 2;

    Planet.scaleX = $increment;

    Planet.scaleY = $increment;

    Planet.scaleZ = $increment;

    2 ClickEdit.

    3 Play the animation.

    Because you assigned time * 2 to the variable $increment, the expression sets

    all three attributes to the value of time * 2 as the animation plays. This makesthe three scale attributes increase at a rate twice as fast as would occur if youassigned them the value of time alone.

    4 Stop and rewind the animation.

    This concludes the example. Before starting the next example, delete thescene and create a new scene.

    Summary

    In this lesson, you learned how to:

    link multiple attributes of the same object with a single expression

    use a variable you defined in an expression

    modify a single assignment to an attribute without changing otherstatements

  • 5/28/2018 Maya -Tutorial (Expressions)

    28/274

    28 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes in two objects

    Controlling attributes in two objectsYou can write an expression to control attributes in two or more objects. Inthe following steps, youll create a cylinder and cone, then rotate eacharound its local X-axis as the animation plays. In other words, each objectwill spin around in place.

    To see an objects local rotation axes, select the object, then chooseDisplayObject ComponentsLocal Rotation Axes.

    To prepare the scene:

    1 From the Modeling menu, choosePrimitivesCreate NURBSCone.

    2 In the Channel Box or elsewhere, name it Cone.

    3 ChoosePrimitivesCreate NURBSCylinder from the Modeling menu.

    4 In the Channel Box or elsewhere, name the cylinder Can.The exact translation and scale of Cone and Can is unimportant in thisexample. Give them roughly the same translation and scale as in the abovefigure.

    5 Select both objects, then chooseDisplayNURBS SmoothnessFine.

    This sets the display smoothness of both objects to fine resolution.

    6 Display the Expression Editor and selectSelect FilterBy Object/AttributeName.

    7 Rewind the animation to frame 0.

  • 5/28/2018 Maya -Tutorial (Expressions)

    29/274

    Using Maya: Hypergraph, Sets & Expressions 29

    Quick Start

    Controlling attributes in two objects

    Expr

    essions

    To create the expression:

    1 Select Can.

    To control attributes in both objects, you can select either object to write theexpression. In fact, any object or node in a scene can be selected when youwrite an expression to control an object other than a particle object. Fordetails on creating expressions to control particles, see Chapter 8, ParticleExpressions.

    2 In the Expression Editor, enter RotCanAndCone in theExpression Namebox.

    This names the expression so you can find it more easily later.

    3 Enter this expression:Can.rotateX = time * 10;

    Cone.rotateX = time * 10;

    This assigns Cans rotateX attribute and Cones rotateX attribute to the valueof time multiplied by 10.

    4 ClickCreate to compile the expression.

    To see the results:

    1 Play the animation.

    Each object rotates around its local X-axis by the degree value resulting fromtime * 10. After 1 second, for example, the rotateX attribute of each object isone degree times 10, or 10 degrees. After 2 seconds, its 2 degrees times 10,or 20 degrees.

    Maya works in degree angle units, by default. You can change the angular

    units to radians by choosingOptionsGeneral Preferences and displayingtheUnitsfolder.

  • 5/28/2018 Maya -Tutorial (Expressions)

    30/274

    30 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes in two objects

    With the animation playing at 24 frames per second, each objects rotateXattribute has these values:

    The values in this chapter are rounded to four significant digits. The actualvalues might have many more digits.

    To see the degree value of Can.rotateX at different frames, select Can,display the Channel Box, and stop the animation at selected frames. TheChannel Box updates its values after you stop the animation.

    To see the degree value of Cone.rotateX at different frames, select Coneinstead of Can. The Channel Box displays values for the selected object.

    2 Stop and rewind the animation.You can edit the expression to make Can rotate slower than Cone.

    To get different results:

    1 Change to the expression to this:

    Can.rotateX = time * 5;

    Cone.rotateX = time * 10;

    2 ClickEdit to compile the expression.

    3 Play the animation.

    Can rotates half as fast as Cone as the animation plays.

    Frame Time Can.rotateX(degrees)

    0 0 0

    1 0.0417 0.417

    2 0.0833 0.833

    3 0.125 1.25

    24 1.0 10

    240 10.0 100

  • 5/28/2018 Maya -Tutorial (Expressions)

    31/274

    Using Maya: Hypergraph, Sets & Expressions 31

    Quick Start

    Controlling attributes in two objects

    Expr

    essions

    4 Stop and rewind the animation.

    5 Close the Expression Editor window.

    This concludes the example.

    This example showed how to write a single expression to control attributesof two different objects. However, you could have written two expressions,one that rotates Can and one that rotates Cone.

    The advantage of creating separate expressions is that youll have twoexpression names, each presumably named after the object and attributeyoure controlling. Having two expression names makes it easier to find theexpression that controls the desired attribute.

    The advantage of using a single expression to control the attributes is that allstatements are in a single expression. You dont need to edit twoexpressions.

    Before starting the next example, delete the scene and create a new scene.

    Summary

    In this lesson, you learned how to:

    control rotateX attributes in two objects using the same expression

    increase the rotation of each object in synch with animation time

    rotate one object at half the speed of the other object

  • 5/28/2018 Maya -Tutorial (Expressions)

    32/274

    32 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes conditionally

    Controlling attributes conditionallyYou can write an expression that takes different actions depending on thevalue of attributes or variables it examines as an animation plays.

    In the following steps, youll increase the scale of a sphere for the first twoseconds of animation, then stop scaling and move it in a global Y-axisdirection for the remainder of the animation.

    To prepare the scene:

    1 From the Modeling menu, choosePrimitivesCreate NURBSSphere.

    By default, this creates a NURBS sphere at the origin with an X scale, Y scale,and Z scale of 1.

    2 From the Channel Box or elsewhere, name the sphere Balloon.

    3 SelectDisplayNURBS SmoothnessFineto set Balloons displaysmoothness to fine resolution.

    4 Display the Expression Editor and selectSelect FilterBy Object/AttributeName.

    5 Rewind the animation to frame 0.

    To create the expression:

    1 Select Balloon.

    2 In the Expression Editor, enter RisingBalloon in theExpression Namebox.

    3 Enter this expression:

    if (time < 2)

    Balloon.scaleY = time;

    This expression is an ifstatement. The if keyword causes the expression tomake a decision based on a comparison of two or more items. In this case,the expression compares the value of time to the value 2.

  • 5/28/2018 Maya -Tutorial (Expressions)

    33/274

    Using Maya: Hypergraph, Sets & Expressions 33

    Quick Start

    Controlling attributes conditionally

    Expr

    essions

    The expression checks whether the value of time is less than two seconds. Ifso, it does the assignment Balloon.scaleY = time. If time is not less than twoseconds, the assignment doesnt occur.

    Notice the indentation of Balloon.scaleY = time under if (time < 2). Mayaignores all indentation, extra spaces, and blank lines between statements. We

    used the indentation to make the expression easier to read. You could havealso written the expression as follows:

    if (time < 2) Balloon.scaleY = time;

    This isnt as easy to read. Consistent, organized spacing is a good habit todevelop. This book shows examples of good spacing style.

    4 ClickCreate to compile the expression.

    Balloon flattens.

    The expression executes when you click theCreatebutton. Because theanimation is at frame 0, animation time is 0. Because time is less than 2,Maya sets Balloon.scaleY equal to the value of time, which equals 0.

    A scaleY value of 0 flattens the object in the Y dimension.

    5 Play the animation.

    The flattened Balloons scale increases along its Y-axis. It inflates as theanimation plays.

    Important

    When you compare the value of time to a number in an expression, Mayainterprets time as seconds rather than milliseconds, minutes, or any otherunit of time. In the example, Maya interprets 2 as 2 seconds.

  • 5/28/2018 Maya -Tutorial (Expressions)

    34/274

    34 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes conditionally

    At 2 seconds, Balloon stops inflating. An expression executes each frame as

    an animation plays. The if statement sets the scaleY attribute of Balloon tothe value of time each frame when the time is less than 2.

    When time equals 2 or more, the if condition is no longer true. The statementthat follows it, Balloon.scaleY = time, no longer executes. The value of thescaleY attribute stays at the last value it had before time became 2,specifically, 1.9583. At 2 seconds of animation time and every momentthereafter, scaleY continues to be 1.9583.

    Recall that this example uses a frame rate of 24 frames/second.

    The time and Balloon.scaleY have these values at various frames:

    The if statements condition, (time < 2), is a comparison. The condition mustbe surrounded by parentheses to isolate it from assignment that follows it.

    Frame Time (seconds) Balloon.scaleY (time)

    0 0 0

    1 0.0417 0.0417

    2 0.0833 0.0833

    3 0.125 0.125

    24 1.0 1.0

    47 1.96 1.9583

    48 2.0 1.9583

    49 2.04 1.9583

  • 5/28/2018 Maya -Tutorial (Expressions)

    35/274

    Using Maya: Hypergraph, Sets & Expressions 35

    Quick Start

    Controlling attributes conditionally

    Expr

    essions

    The < in the condition is a relational operator. A relational operator testshow one value relates to another. In the example, the < tested whether timeis less than 2.

    Besides the < operator shown in this example, there are several otherrelational operators such as >, >=, ==, and so on. See Arithmetic, logic, andrelational operators in Chapter 5.

    6 Stop and rewind the animation.

    Balloon flattens again because the scaleY attribute becomes 0 when yourewind the animation. Time is 0, so scaleY is 0.

    You can make Balloon rise after it inflates by adding a second if statement tothe expression.

    To add another if statement to the expression:

    1 Change the expression to this:

    if (time < 2)

    Balloon.scaleY = time;

    if (time >= 2)

    Balloon.translateY = time;

    2 ClickEdit to compile the expression.

    3 Play the animation.

    Balloon inflates for 2 seconds. After 2 seconds, Balloon stops inflating and its

    position skips from a Y-axis position of 0 to 2. Youll eliminate the motionskip in a later step.

    The second if statement increases the translateY position of Balloon after theanimation time rises above two seconds. The >= symbols mean greater thanor equal to. Whenever time is greater than or equal to 2, the expressionassigns Balloons translateY the value of time. The translateY value thereforeincreases for the rest of your animations playback range.

    Notice that a semicolon ends each statement. Forgetting a semicolon aftereach statement causes a syntax error, and the changes youve made to theexpression wont take effect.

  • 5/28/2018 Maya -Tutorial (Expressions)

    36/274

    36 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes conditionally

    4 Stop and rewind the animation.

    Balloon flattens but doesnt return to the origin. (If Balloon has risen out ofview, adjust your camera to see it.)

    Balloon doesnt return to the origin because the expression doesnt assignBalloon a starting point for the beginning of the animation.

    5 To make Balloon return to the origin, change the expression to this:

    if (time == 0)

    Balloon.translateY = 0;

    if (time < 2)

    Balloon.scaleY = time;

    if (time >= 2)

    Balloon.translateY = time;

    The new first statement sets Balloon.translateY to 0 whenever time equals 0.The == symbols mean is equal to. In conditional statements, be careful to type

    == rather than =. The = symbol means assign the value to.

    Important

    Always examine the Script Editor for error messages after you edit anexpression and click theCreatebutton. If you alter a previously successfulexpression and a syntax error occurs, Maya executes the previoussuccessful expression when you play the animation. This might make youbelieve your editing changes took effect.

  • 5/28/2018 Maya -Tutorial (Expressions)

    37/274

    Using Maya: Hypergraph, Sets & Expressions 37

    Quick Start

    Controlling attributes conditionally

    Expr

    essions

    Note that you can put the three statements in any order in this example.When Maya plays each frame, it executes each statement in the expression inthe order listed. In this example, the statements work independently, so theirorder doesnt matter.

    We put the statements in the order of time execution because its easier tosee the logic of the expression. If you ever need to change the expression,youll be able to grasp the expressions actions more quickly.

    6 ClickEdit.

    7 Stop and rewind the animation again.

    The flattened Balloon returns to its correct position at the origin.

    8 Play the animation.

    Balloon inflates for two seconds, then rises.

    As mentioned before, Balloon skips from Y-axis position 0 to 2 after twoseconds of animation play. You can eliminate the skipping and make

    Balloon rise smoothly from the origin.

    To eliminate the motion skip:

    1 Stop and rewind the animation.

    2 Change the expression to this:

    if (time == 0)

    Balloon.translateY = 0;

    if (time < 2)

    Balloon.scaleY = time;

    if (time >= 2)

    Balloon.translateY = time - 2;

    3 ClickEdit.

    4 Play the animation.

  • 5/28/2018 Maya -Tutorial (Expressions)

    38/274

    38 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes conditionally

    Balloon inflates for 2 seconds, then rises slowly with time from its position atthe origin.

    When time is greater than or equal to 2, the translateY position of Balloonbecomes 2 minus 2, which is 0. As time increases beyond 2 seconds, thetranslateY position increases in the same increments that time increases.

    5 Stop and rewind the animation.

    The expression achieved the desired result, but its more complicated thannecessary. You can use an if-else statement to make the statement morecompact and easier to read.

    To use an else statement instead of multiple if statements:

    1 Change the expression to this:if (time == 0)

    Balloon.translateY = 0;

    if (time < 2)

    Balloon.scaleY = time;

    else

    Balloon.translateY = time - 2;

    2 ClickEdit.

    3 Play the animation.

    The else keyword sets Balloon.translateY to time - 2 when (time < 2) is false.In English terms, the combination of the if and else statements says, If time

    is less than two seconds, set Balloon.scaleY to the value of time. Otherwise(when time is greater than or equal to two seconds), set Balloon.translateY totime minus two.

  • 5/28/2018 Maya -Tutorial (Expressions)

    39/274

    Using Maya: Hypergraph, Sets & Expressions 39

    Quick Start

    Controlling attributes conditionally

    Expr

    essions

    At any instant in the animations playback, either Balloon.scaleY = timeexecutes or Balloon.translateY = time - 2 executes. Under no circumstancescan they both execute. The else statement executes only when the ifcondition that precedes it is false.

    Note that we added a blank line between the first if statement and the if-elsestatement combination. This has no effect on the execution of the statements.We put it there to emphasize that the two if statements are unrelated.

    The first if statement executes whenever time equals 0. It is unrelated to theif-else statements.

    Using else statements instead of multiple if statements makes an expressionsimpler to read. If you use an if-else construction instead of a lengthy list of

    if statements, youll also improve the execution speed of the expression. Thisimproves your animations playback and rendering speed.

    Either expression is valid. If using the if-else construction seems confusing,stick with multiple if statements.

    You can accomplish most expression animation tasks with several ifstatements strung after one another.

    4 Stop and rewind the animation.

    You can refine the expression to make it even easier to read.

    To make the expression easier to read:

    1 Change the expression to this:if (time < 2)

    {

    Balloon.translateY = 0;

    Balloon.scaleY = time;

    }

    else

    Balloon.translateY = time - 2;

    We removed this statement from the previous version of the expression:

    if (time == 0)

    Balloon.translateY = 0;

    In its place, we put the statement Balloon.scaleY = time in a segment

    enclosed by the braces { and }. Maya evaluates both the statements betweenthe braces if the condition (time < 2) is true.

    2 ClickEdit.

  • 5/28/2018 Maya -Tutorial (Expressions)

    40/274

    40 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes conditionally

    3 Play the animation.

    The animation plays exactly as before with the new expression.

    When the animation time is less than two seconds, not only does Maya setBalloon.scaleY to time, it sets Balloon.translateY to 0. Balloon has a positionat the origin until the animation time is greater than or equal to 2 seconds.

    Setting Ball.translateY to 0 here instead of in a separate if statement makesthe expression easier to read and comprehend.

    As in the previous version of the expression, if time is greater than or equalto 2, Maya executes the else statement.

    Note that you can put multiple statements between braces for an else

    statement, just as you do for an if statement.4 Stop and rewind the animation.

    You can further refine the animations appearance by expanding Balloonmore slowly.

    To slow Balloons expansion:

    1 Change the expression to this:

    if (time < 2)

    {

    Balloon.translateY = 0;

    Balloon.scaleY = time * 0.6;

    }else

    Balloon.translateY = time - 2;

    Only one statement is different, Balloon.scaleY = time * 0.6. The asterisk (*)multiplies time by 0.6.

    2 ClickEdit.

    3 Play the animation.

  • 5/28/2018 Maya -Tutorial (Expressions)

    41/274

    Using Maya: Hypergraph, Sets & Expressions 41

    Quick Start

    Controlling attributes conditionally

    Expr

    essions

    The scaleY attribute increases at 60% of the value of time, so Balloonexpands slower during playback. (The number 0.6 equals 60%.) By the timeBalloon starts to rise, it has expanded to the size of a typical balloon.

    How do you know whether to multiply time by 0.6 or some other number?You dont. In cases like this, you need to experiment.

    For example, you might multiply by various percentages such as 0.2, 0.5,0.75, and finally 0.6. The 0.6 creates a life-like balloon shape at two seconds.

    4 Stop and rewind the animation.

    You can further refine Balloons appearance by eliminating the flattenedBalloon that appears at the origin when you rewind the animation. You canalso scale Balloon at different rates along each of its three axes.

    To further refine Balloons appearance:

    1 Change the expression to this:if (time < 2)

    {

    Balloon.translateY = 0;

    Balloon.scaleY = time * 0.6;

    Balloon.scaleX = time * 0.5;

    Balloon.scaleZ = time * 0.5;

    }

    else

    Balloon.translateY = time - 2;

    2 ClickEdit.

    Balloon disappears from view because its scale attributes are 0.

    The scaleX, scaleY, and scaleZ attributes are 0 at frame 0 because time is 0.Any number multiplied by 0 is 0.

    3 Play the animation.

  • 5/28/2018 Maya -Tutorial (Expressions)

    42/274

    42 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Controlling attributes conditionally

    As time increases, the value of Balloons scale attributes increase. Becausethe expression sets scaleX and scaleZ to 50% of the value of time, thesedimensions scale slower than scaleY, which is set to 60% of the value of time.

    Balloon scales faster in height than in width or depth. This is true for manyreal balloons.

    4 Stop and rewind the animation.

    This concludes the example.

    Summary

    Using an expression is a combination of logic and experimentation. Problemsolving starts with breaking a task into smaller problems you can solve andlater refine.

    In this lesson, you learned how to:

    control an attribute conditionally with an if statement

    use good spacing and indentation for expressions

    use relational operators such as

  • 5/28/2018 Maya -Tutorial (Expressions)

    43/274

    Using Maya: Hypergraph, Sets & Expressions 43

    Quick Start

    Notes on the predefined time variable

    Expr

    essions

    In the preceding examples we didnt include comments in expressionsbecause we explained them line by line. When you write your ownexpressions, include comments with statements to help document how theexpression works.

    This will help you or someone else understand how your expression workslater if the need to enhance it arises. See Comments in expressions inChapter 5.

    Notes on the predefined time variableThe lessons in this chapter use a starting frame number of 0. In your work,

    youll typically create an animation with a starting frame number of 1.Because the examples use Mayas default frame rate of 24 frames per second,time is 0.0417 at frame 1. Because of this small offset from 0, the exampleswould have required more steps and instructions to work with frame 1 asthe starting frame.

    For instance, in the first example of the chapter, suppose you set the startingframe of the animation to 1. The expression in the example follows:

    Ball.scaleY = time + 1;

    If you rewind the animation, the expression executes and sets the initialvalue of Balls scaleY attribute to time + 1, which equals 0.0417 + 1, or 1.0417.Because Balls scaleY attribute was 1 when you created it, rewinding the

    animation sets scaleY to a value 0.0417 larger than its initial value.This discrepancy means the Ball scaleY is larger than its scaleX and scaleZattributes in the first frame of the animation. Though the difference is notsubstantial in this example, other cases might be more significant.

    To start your animation at frame 1 and get the same result as the example,you can subtract 0.0417 from the attribute:

    Ball.scaleY = (time - 0.0417) + 1;

    When you rewind the animation, the expression sets Balls scaleY value to(0.0417 - 0.0417) + 1. This equals 1, its original scaleY value.

    When you use the predefined time variable, be aware of the starting framenumber and the associated time value.

  • 5/28/2018 Maya -Tutorial (Expressions)

    44/274

    44 Using Maya: Hypergraph, Sets & Expressions

    Quick Start

    Notes on the predefined time variable

    After doing the lessons in this chapter, remember to change your TimeSliders starting frame, ending frame, and frame rate to the desired valueswhen you start other projects. To do this, selectOptionsGeneralPreferencesand display the appropriate tabs in the General Preferenceswindow.

  • 5/28/2018 Maya -Tutorial (Expressions)

    45/274

    Using Maya: Hypergraph, Sets & Expressions 45

    Expr

    essions

    5 Expression SyntaxExpressions use the syntax of the Maya Embedded Language (MEL).Though MEL is a scripting language, youll find the syntax easy to learneven if youve never programmed. Mastering the rules of syntax is essentialto writing expressions without errors.

    This chapter describes the following topics:

    Expressions and MEL on page 46

    Elements of an expression on page 47

    Attributes on page 49

    Variables on page 56

    Constants on page 62

    Arithmetic, logic, and relational operators on page 63

    Operator precedence on page 68

    Conditional statements on page 69 General syntax rules on page 73

    Comments in expressions on page 75

    You can use an expression torotate each child joint basedon the root joints keyframedrotation.

    Tristan Ikuta

  • 5/28/2018 Maya -Tutorial (Expressions)

    46/274

    46 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Expressions and MEL

    Programming features on page 75

    Common expression errors on page 95

    Expressions and MELExpressions have a different purpose from MEL commands and MELscripts. You enter a MEL command to do a single action, for example, tocreate a sphere.

    A MEL script is a list of commands you create to do a sequence of actions,for instance, create a wall-shaped object and apply a brick texture to it.

    Because you store a MEL script in a file on disk, you can run a script indifferent scenes and different work sessions, whether today or next year.

    An expression animates one or more attributes over time in a single scene.By default, an expression executes each frame as an animation plays. Afteryou create an expression, it executes whenever you play the animationincluding when you play the animation after saving, closing, and reopeningthe scene.

    A MEL command or script is not part of a scene after you execute it. Youmust execute it again to repeat the action.

    Sometimes its useful to exectute MEL commands and scripts in expressions.See Executing MEL commands in an expression on page 137 for details.

    The following pages describe expression syntax elements such as arithmeticoperators you can use to set and compare attributes. If you have troubleunderstanding the syntax descriptions, refer to a C programming guide forbeginners. Except for attribute names, the syntax elements have the samedefinitions as their counterparts in C. Attribute names do not exist in C.

    If youre familiar with a programming language such as C, Pascal, or Basic,be sure to see Programming features on page 75.

    Action Typical use

    MEL command Does one action

    MEL script Does several actions

    Expression Animates attribute values as an animation plays

  • 5/28/2018 Maya -Tutorial (Expressions)

    47/274

    Using Maya: Hypergraph, Sets & Expressions 47

    Expression Syntax

    Elements of an expression

    Expr

    essions

    Elements of an expressionAn expression is made of one or more statements. Statements follow therules of algebra, so theyll seem familiar if youve studied math. Eachstatement has several elements as in the following example:

    Detailed explanations follow the summary definitions:

    Attribute name The name of the attribute set by the statement. In theexample, Ball.rotateZ is the attribute name of the rotateZattribute of an object named Ball.

    Assignment

    operator The = to the right of an attribute name. This symbol assignsthe attribute the result of the statement on the right side of=. In the example, Ball.rotateZ receives the value of thestatement sin(time) + 6. (Ignore what this assignment does;

    its for illustration only.) You can also use = to assign a valueto a variable.

    Function A special word that you provide with an entry called anargument. In this example, the argument is time. Based onthe value of the argument, Maya does a calculation for thefunction and returns a new value or takes some other action.

    In the example, the function sin(time) returns the sine of thevalue of time, which evaluates to a number between -1 and1.

    Maya has many convenient built-in functions andcommands that do math calculations, conversions, and so

    on. See Chapter 9 for details.

    Attribute name ConstantFunction

    Assignment operator Arithmetic operator

    Ball.rotateZ = sin(time) + 6;

    VariableStatement

    Terminator

  • 5/28/2018 Maya -Tutorial (Expressions)

    48/274

    48 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Elements of an expression

    Variable A variable is a symbolic name that stands for a changingvalue. You can assign a value to a variable or read avariables value. The variable timeis a predefined Mayavariable that contains the animation time at the currentframe. You can read but not set the value of time.

    Arithmetic, logic,

    or relational

    operator An operation such as + or < (less than).

    Constant An unchanging number, for example, 6.1 or 90.

    Terminator A semicolon (;) that marks the end of a statement. Anexpression can have an unlimited number of statements.You must end each statement with a semicolon.

    Each expression usually has an attribute name, assignment operator (=),expression value assigned to the attribute, and a statement terminator (;).Other elements are optional.

    Example

    Heres an expression with the fewest elements possible:

    The expression has an attribute, assignment operator (=), value assigned tothe attribute, and a statement terminator (;). The expression sets Balls Yscale to 5 grid units. When you play the animation, Balls Y scale stays fixedat 5 regardless of the Y scale value you gave it when you created it.

    Ball.scaleY = 5;

    Value assigned

  • 5/28/2018 Maya -Tutorial (Expressions)

    49/274

    Using Maya: Hypergraph, Sets & Expressions 49

    Expression Syntax

    Attributes

    Expr

    essions

    AttributesAn attribute is a characteristic of an object or other item in a scene. There aremany ways to set attributes in Mayawith the Attribute Editor, ChannelBox, menu selections, and of course, expressions. You can set attributes tocontrol virtually anything in your animation.

    There are three types of attributes you work with in Maya:

    static

    dynamic

    custom

    Static and dynamic attributes have a predefined purpose. They are standardattributes Maya provides for objects and items that make up a scene. Customattributes are attributes you define for an object.

    Static attributes

    Static attributes are attributes an object has by default. They exist themoment you create the object and throughout its lifetime.

    For example, the transform node of a NURBS sphere has static attributesscaleX, scaleY, scaleZ, rotateX, and so on. You can set the values of theseattributes with the Attribute Editor, Channel Box, expressions, and othertechniques after you create the object.

    Dynamic attributes

    Dynamic attributes have predefined names and purposes, but Maya addsthem to an object in response to your user interface selections.

    For example, suppose you create a particle object and display its particleshape folder in the Attribute Editor. If you click one of the following buttonsin the Add Dynamic Attributes section of the Attribute Editor, Maya adds adynamic attribute to the node:

    Clicking theGeneralbutton lets you add a custom attribute (see the nexttopic). Clicking any of the other buttons lets you add one or more dynamicattributes with names that are the same or similar to the button name.

  • 5/28/2018 Maya -Tutorial (Expressions)

    50/274

    50 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Attributes

    An object has no dynamic attributes unless your actions cause Maya to addthem to the object. By adding only required attributes, Maya runs faster.

    When you add a dynamic attribute to an object, the attribute appears in theAttribute editor for the selected object or node.

    Custom attributes

    Custom attributes are attributes you optionally add from the New folder ofthe Add Attribute window.

    Note

    Because soft body geometry is a particle shape node coupled withgeometry, a soft body has the same static and dynamic attributes as aparticle object.

  • 5/28/2018 Maya -Tutorial (Expressions)

    51/274

    Using Maya: Hypergraph, Sets & Expressions 51

    Expression Syntax

    Attributes

    Expr

    essions

    Such attributes have no direct effect on any characteristic of an object.Theyre often used to control a combination of other attributes. You mightalso use a custom attribute as a variablea place to store a valuetemporarily to be read by other attributes.

    When you add a custom attribute to an object, it appears in the AttributeEditor and Channel Box for the object or node. Though custom attributes aredynamically added to an object, we refer to them as custom to distinguishthem from the built-in dynamic attributes.

    See Assigning to a custom attribute in Chapter 8 for details on how to addand use a custom attribute.

    Attribute namesStatic, dynamic, and custom attributes follow the same naming conventionsand represent the same types of data.

    A full attribute name has this format:

    object.attribute

    where object is the name of the object node, and attribute is the name of theattribute. A period (.) separates the name of the object and attribute.

    You must spell the object and attribute name with uppercase and lowercaseletters as they appear in the Expression Editors Objects and Attributes lists.You cannot spell attribute names with the common English spellings shown

    in the Attribute Editor or by default in the Channel Box.See Using attribute names in expressions in Chapter 6 for more details.

    Example

    Ball.scaleY

    Data types of attributes

    Each attribute has a data type that specifies the type of values you can use tocontrol it in an expression. This is true for static, dynamic, and customattributes.

  • 5/28/2018 Maya -Tutorial (Expressions)

    52/274

    52 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Attributes

    Attributes youll work with in expressions have these data types:

    The most common attribute data type is floating point. In mathematics,floating point numbers are also called real numbers. Often, such numbershave a decimal point.

    Booleans are also common data types in attributes. Integer data types arerarely used.

    Particle shape nodes have these additional attribute data types:

    Data type Meaning Example attribute Example data

    float floating point numbers Balloon.scaleY -2.3333333333

    integer signed whole numbers Ball.sections 16

    Boolean on or off selection Ball.visibility on

    Data type Meaning Example attribute Example data

    vectorarray

    array of vectors FireShape.position

    floatarray

    array of floatingpoint numbers

    FireShape.lifespan 1.3331.6662.3331.333

    Note

    Scientists often refer to a vector as a quantity that specifies both amagnitude and direction. In Maya, a vector is simply a related group ofthree floating point numbers that set an attribute or variable.

  • 5/28/2018 Maya -Tutorial (Expressions)

    53/274

    Using Maya: Hypergraph, Sets & Expressions 53

    Expression Syntax

    Attributes

    Expr

    essions

    Vector array data types are useful for animating position, velocity,acceleration, color, and other particle attributes made of three components.

    Float array attributes are useful for setting lifespan, opacity, and otherparticle attributes that have a single number value.

    Attributes having a vector array or float array data type are also called perparticle attributes. See Chapter 8 for details on working with particleattributes.

    If you have programming experience, note that for vector array data types,Maya represents the specified attribute for each particle of the object with asingle element of an array. Each element is made of three floating pointnumbers. In a float array, Maya represents the specified attribute for each

    particle with a vector array element thats a floating point number.

    Data types of static and dynamic attributes

    Static and dynamic attributes have predefined data types. To learn theattributes data type, select the node containing it. In the Attribute Editor,find the attribute name and examine its data format.

    Note

    In expressions, you must type a vector in double angle brackets (>).For example, type for a vector having 3, 0, and 5 as its left,middle, and right component.

  • 5/28/2018 Maya -Tutorial (Expressions)

    54/274

    54 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Attributes

    Heres an example display of attributes with floating point, Boolean, andinteger data types:

    A floating point attribute shows a value that includes a decimal point. Mostnumerical attributes in Maya are floating point.

    A Boolean attribute has a checkbox or other user interface item for turning iton or off.

    An integer attribute has no decimal point. Integer attributes are rare inMaya.

    The data type of an attribute limits what type of value you can enter for theattribute in the Attribute Editor and in expressions. For example, because adirectional lightsDepth Map Filter Size attribute is an integer, you cannotenter a decimal point in its text entry box or assign it a decimal quantity inan expression.

    For a floating point attribute, you can omit the decimal point. The AttributeEditor automatically inserts a decimal point in the attributes text field afteryou press the Enter key. For example, if you type 3 for a floating point entry,

    the Attribute Editor replaces 3 with 3.0000.

    Floating point

    Boolean

    Integer

  • 5/28/2018 Maya -Tutorial (Expressions)

    55/274

    Using Maya: Hypergraph, Sets & Expressions 55

    Expression Syntax

    Attributes

    Expr

    essions

    An expression also automatically converts an integer to a floating pointvalue when appropriate. See Data type conversions in Chapter 7 fordetails.

    Only particle objects, not geometric objects, have vector array and float arrayattributes. The static vector array attributes for particle objects are position,velocity, and acceleration. These are also called per particle attributesbecause you can set the attribute for each particle to different values.

    Maya has other attribute data types that are irrelevant to the use ofexpressions. For example, Maya has a matrix data type that is useful only inMEL scripting and API programming.

    Data types of custom attributes

    When you add a custom attribute to an object withModifyAdd Attribute,you choose whether its data type is floating point, integer, Boolean, orvector. Vector attributes are commonly used with particle shape nodes.

    Assigning a value to an attribute

    You assign a value to an attribute using the = assignment operator. Staticand dynamic attributes have data types established by Maya. You do notdefine their data type.

    Because you choose the data type of custom attributes when you add themwithModifyAdd Attribute, you do not define their data type either.

    You can assign a value to any attribute. If the attribute is dynamic or custom,though, you must add the attribute to the object before you can assign it avalue in an expression.

    Become familiar with the purpose of an attribute by working with it in theAttribute Editor, Channel Box, or other parts of Maya before assigning it avalue in an expression. Its best to know the behavior you can expect fromthe attribute in case you write your expression incorrectly.

    Note

    For rigid bodies, you can read but not write the velocity, angularVelocity,and force attributes.

  • 5/28/2018 Maya -Tutorial (Expressions)

    56/274

    56 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Variables

    Assigning to a float or integer attributeAn assignment operation is a statement, so you must terminate it with asemicolon (;).

    Examples

    Cone.scaleY = 5.3;

    This assigns 5.3 to the floating point scaleY attribute of Cone.

    Ball.translateY = time;

    This assigns the value of time to the floating point translateY attribute ofBall.

    Ball.scaleX = Ball.scaleY = Ball.scaleZ = 2;

    This assigns 2 to the floating point scaleX, scaleY, and scaleZ attributes ofBall. As the example shows, you can use an assignment operator severaltimes in a statement to set multiple attributes to the same value.

    Assigning to a vector attribute

    You can assign values to all three components of a vector attribute, or just toa single component.

    See Assigning to vectors and vector arrays in Chapter 8 for details onassigning values to vector attributes. Only particle shape nodes have vectorattributes.

    Note that you cannot assign a vector to three related scalar attributes such asscaleX, scaleY, and scaleZ. For example, you cant do this:

    Ball.scale = ;

    You must assign to each attribute separately:

    Ball.scaleX = 1;

    Ball.scaleY = 2;

    Ball.scaleZ = 0;

    Variables

    A variable is a symbolic name that stands for a constant or changing value.There are two types of variables, predefined and custom.

    Maya creates and maintains predefined variables. Custom variables arevariables you can create to store data in an expression.

  • 5/28/2018 Maya -Tutorial (Expressions)

    57/274

    Using Maya: Hypergraph, Sets & Expressions 57

    Expression Syntax

    Variables

    Expr

    essions

    Keep in mind that attributes, not variables, set object and componentbehavior in Maya. You can use variables to as temporary storage forworking with the attributes.

    Data types of variables

    Variables can be one of these types of data:

    The most common data type of variables is floating point. Integer data typesare rarely used. Booleans are commonly used in attributes, but not allowedin variables. Vector variables are useful in expressions for particle shapeattributes.

    Animators with programming experience sometimes use string variables.Quote marks (" ") are required with strings. See String usage on page 90for details.

    For a custom variable you create in an expression, you must declare the datatype as described in Custom variables on page 59.

    Predefined variables

    Maya maintains values in two predefined variables as an animation plays:

    Data type Meaning Examples Definingkeyword

    float floating point numbers 392.6, -0.667 float

    integer signed whole numbers 10, -5, 0 int

    vector vector made of threefloating point numbers

    vector

    string one or more characters Whats up, chief? string

    Variable Contents Data type

    frame number of frames the animation has played float

    time time in seconds the animation has played float

  • 5/28/2018 Maya -Tutorial (Expressions)

    58/274

    58 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Variables

    Your expressions can read, but not set, the value of time and frame. Thesevariables are floating point values that are useful for animating an attributeas an animation plays.

    The time updates as an animation plays. It contains the elapsed number ofseconds from the first frame to the current frame. The value increases withthe increasing frame number.

    At the default animation playback rate of 24 frames per second, time hasthese values, rounded to four decimal places:

    If you need to change the playback rate, chooseOptionsGeneralPreferences. Expand the General Preferences window, display the Unitsfolder, and choose the desired rate from theTimemenu.

    Regardless of what animation playback rate you choose, you can find thetime elapsed in the animation at any frame with this formula:

    For example, if the frame rate is 24 frames/second, and the animation is atframe 1, the elapsed time is 1 divided by 24, or 0.0417. At frame 6, theelapsed time is 6 divided by 24, which equals 0.25.

    If the frame rate is 30 frames/second and the animation is at frame 1, theelapsed time is 1 divided by 30, which equals 0.0333. At frame 6, elapsed

    time is 6 divided by 30, which equals 0.2.

    Frame Time (seconds)

    0 01 0.0417

    2 0.0833

    3 0.125

    24 1.0

    240 10.0

    time frame

    rate---------------=

  • 5/28/2018 Maya -Tutorial (Expressions)

    59/274

    Using Maya: Hypergraph, Sets & Expressions 59

    Expression Syntax

    Variables

    Expr

    essions

    Theres an advantage to writing an expression using the value of time ratherthan frame: You wont need to modify your expression if you change youranimations frame rate.

    Note that time is always 0 at frame 0. As each frame plays, the time increasesin increments resulting from the frame rate.

    Its impossible to set time to a value other than 0 at frame 0. If you setMayas frame range to begin at a negative number, time has a negativevalue.

    Examples

    Ball.translateY = time/2;

    This sets the Balls Y translation equal to the value of time divided by 2 asthe animation plays. This make the Ball move in a Y direction as theanimation time increases.

    Ball.scaleY = frame/2;

    This sets the Balls Y scale equal to the value of frame divided by 2 as theanimation plays. The Ball scales along its Y axis as the animation framenumber increases.

    Custom variables

    You can declare and use variables to store a constant or changing value.These work like their counterparts in programming languages andspreadsheet programs.

    Though programming languages use such variables abundantly, you mightnot need to use them at all in many expressions.

    Declaring variables

    Each custom variable name must begin with a dollar sign character ($). Afterthe $, you can use alphabetical, numerical, and underscore characters. Youcannot include spaces in the names.

    Variable names are type case sensitive. In other words, $temp is a differentvariable name than $Temp.

  • 5/28/2018 Maya -Tutorial (Expressions)

    60/274

    60 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Variables

    Examples

    float $object_height;

    This declares $object_height as a floating point variable.

    int $counter;

    This declares $counter as an integer.

    vector $top_velocity;

    This declares $top_position as a vector variable.

    Assigning a value to an integer or float variable

    To assign a value to a variable, you use = as an assignment operator. Anassignment operation is a statement, so you must end it with a semicolon (;).

    Examples

    float $counter = 5.3;

    This declares a floating point variable named $counter and gives it an initialvalue of 5.3.

    $height = 6;

    This declares a floating point variable named $height and gives it an initialvalue of 6. This example shows you can skip declaring the variables datatype. When you assign a variable a value, Maya assumes the variable is

    floating point unless you specify a different data type.$pi = 3.1415927;

    $twist = $pi;

    These statements show you can assign the value of one variable to anothervariable. The first statement assigns 3.1415927 to $pi. The second statementassigns the contents of $pi, 3.1415927, to $twist.

  • 5/28/2018 Maya -Tutorial (Expressions)

    61/274

    Using Maya: Hypergraph, Sets & Expressions 61

    Expression Syntax

    Variables

    Expr

    essions

    Assigning a value to a vector variable

    You can assign values to all three components of a vector variable, or just toa single component.

    See Assigning to vectors and vector arrays in Chapter 8 for details onassigning values to vector variables. Such variables are useful for working

    with particle shape node attributes.

    Using custom variables globally

    Typically, youll use variables within a single expression. If you want tocreate and maintain a custom variable in one expression, but use it inanother expression, you must declare it as a global variable.

    Example

    global float $counter;

    You can thereafter set or read the value of this variable in any otherexpression in the scene.

    If you create a variable with the same name in two expressions, the twovariables are separate and unrelated. For example, suppose you create avariable named $timer in two expressions. Assigning a value to one of the$timer variables has no effect on the others value.

    Important

    If you misspell an existing declared variable name and assign it a value, asyntax error wont be generated for the undeclared variable. Because Mayaautomatically provides a data type for an undeclared variable if its on theleft side of the assignment operator, the misspelled variable will beinterpreted as a newly added variable. Undeclared variables on the rightside of the assignment operator do generate error messages.

    Check spellings of variables if your expression isnt working as expected.

    In the following example, the misspelling in the final statement generatesan error but not the misspelling in the statement before it:

    int $start;

    int $end;

    int $interrupt;

    $starrrt = 1;

    $end = $interrupppt;

  • 5/28/2018 Maya -Tutorial (Expressions)

    62/274

    62 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Constants

    If you declare and initializea global variable in a single statement, you caninitialize it to a numerical constant or string only.

    Examples

    global float $counter = 3;

    This initializes $counter to 3.

    global float $counter = time;

    This causes an error because time is a variable.

    If you declare and initialize a global variable in a single statement, thestatement executes only when Maya compiles the expression. Maya compiles

    an expression when you click theCreateorEditbutton in the ExpressionEditor, or when you open a scene containing a previously createdexpression.

    Example

    global float $counter = 3;

    print($counter+"\n");

    $counter = 1000;

    print($counter+"\n");

    When Maya compiles the expression, it sets $counter to 3, prints 3, sets$counter to 1000, then prints 1000.

    During playback, each execution of the expression skips the first statement,

    so $counter never receives the value 3. The expression prints 1000, sets$counter to 1000 again, and prints 1000 again.

    ConstantsA constant is an unchanging number or variable.

    Examples

    Ball.translateY = 6.1.

    This statement sets Balls translateY attribute to the constant number 6.1.

    float $pi = 3.1415927;

    Ball.rotateY = $pi;

    These statements set the value of Balls rotateY attribute to the value of thevariable $pi. The variable $pi represents the constant 3.1415927.

  • 5/28/2018 Maya -Tutorial (Expressions)

    63/274

    Using Maya: Hypergraph, Sets & Expressions 63

    Expression Syntax

    Arithmetic, logic, and relational operators

    Expr

    essions

    Arithmetic, logic, and relational operatorsYou can use the following operator symbols to add, subtract, multiply,compare, and do other actions to variables and attributes.

    Arithmetic operators

    Integers and floats

    For integer and floating point attributes and variables, the above arithmeticoperators work according to the rules of basic math. Note that the modulusoperator (%) calculates the remainder of division.

    ExamplesCar.translateX = time / 2.0;

    This moves the Car in an X direction as the time increases in the animation.By dividing time by 2.0, you move the object half as fast as if you used timealone.

    Car.translateX = 7 % 3;

    This assigns Car.translateX the value 1, the remainder of 7 divided by 3. Thenumber 7 divided by 3 equals 2 with a remainder of 1.

    Car.translateX = 8.8 % 4.2;

    This assigns Car.translateX the value 0.4, the remainder of 8.8 divided by 4.2.

    The number 8.8 divided by 4.2 equals 2 with a remainder of 0.4.Car.translateX = 0.5 % 3;

    Symbol Meaning Used with these data types

    + plus integer, float, vector, string

    - minus or negation integer, float, vector

    * for integers and floats: multiplyfor vectors: dot product

    integer, float, vector

    / divided by integer, float

    % remainder of division integer, float

  • 5/28/2018 Maya -Tutorial (Expressions)

    64/274

    64 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Arithmetic, logic, and relational operators

    This assigns Car.translateX the value 0.5, the remainder of 0.5 divided by 3.The number 0.5 divided by 3 equals 0, with a remainder of 0.5.

    Vectors

    For operations between vector attributes and variables, the * operatorperforms the dot product. The dot product multiplies correspondingcomponents of each vector, then adds the components to create a singlefloating point number result.

    For + and - operators, each component of one vector is operated on by itscounterpart component in the other vector.

    For operations between a vector and an integer or floating point number,

    each component of the vector is operated on by the integer or floating pointnumber.

    Examples

    Suppose youve initialized these vectors:

    vector $A = ;

    vector $B = ;

    vector $C;

    float $myfloat;

    You then use the following statements (in different expressions, not insequential order):

    $C = $A + $B;

    This assigns $C the value >.

    $C = $B - $A;

    This assigns $C the value .

    $myfloat = $A * $B;

    This assigns $myfloat the value (1*2) + (2*3) + (3*4), which equals 20.Multiplying two vectors gives the dot product of the vectors.

    $C = 3 * $A;

    This assigns $C the value . Each component of the vector ismultiplied by 3 to create a vector result.

  • 5/28/2018 Maya -Tutorial (Expressions)

    65/274

    Using Maya: Hypergraph, Sets & Expressions 65

    Expression Syntax

    Arithmetic, logic, and relational operators

    Expr

    essions

    StringsFor details on how to use the + operator with strings, see String usage onpage 90.

    Relational operators

    Youll often use relational operators to compare the value of variables andattributes in conditional statements. See Conditional statements on page69.

    Integers and floats

    For integer and floating point attributes and variables, the above relationaloperators work according to the rules of algebra.

    Note

    Maya handles integer and Boolean attributes in an expressionmathematically as floating point numbers. After the expression executes,Maya converts the floating point number to the proper data type.

    If your expression does arithmetic on an integer or Boolean attribute andyou display the attributes contents in the Script Editor, youll see floatingpoint values. After the expression executes, Maya assigns an appropriate

    integer or Boolean value to the attributes you set in the expression textfield.

    Maya handles integer and Boolean variables within an expressionmathematically as integer and Boolean data types.

    Symbol Meaning Used with these data types

    < less than integer, float, vector

    > greater than integer, float, vector

    == equal to integer, float, vector

    != not equal to integer, float, vector

    >= greater than or equal to integer, float, vector

  • 5/28/2018 Maya -Tutorial (Expressions)

    66/274

    66 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Arithmetic, logic, and relational operators

    Examples

    if (time > 10)

    Sphere.translateX = 3;

    When the animation time is greater than 10 seconds of play, the expressionsets the Spheres translateX attribute to 3. It stays fixed in this positionthereafter. See Conditional statements on page 69 for details on the ifcondition in this and following examples.

    if (Ball.scaleY == 3)

    Cone.scaleY = 6;

    If Balls scaleY attribute is equal to 3, Maya sets Cones scaleY attribute to 6.

    Vectors

    If you use the == or != operators between two vector attributes or variables,Maya compares the corresponding components of each vector. In contrast,the >, >=,

  • 5/28/2018 Maya -Tutorial (Expressions)

    67/274

  • 5/28/2018 Maya -Tutorial (Expressions)

    68/274

    68 Using Maya: Hypergraph, Sets & Expressions

    Expression Syntax

    Operator precedence

    Notice that each condition is grouped in parentheses, and the pair ofconditions are enclosed again in parentheses. If you use multiple conditionswith logical operators, you must enclose all the conditions in parentheses forthe if statement.

    If you omit the outer pair of parentheses as in the following example, anerror message occurs:

    if (time > 5) && (time < 10)

    Ball.scaleZ = time;

    Example 2

    if ((Ball.translateX < 5) || (Ball.translateY > 10))

    Ball.scaleZ = time;

    This sets Balls scaleZ attribute to the value of time in either of twoconditions: when Balls translateX attribute is less than 5 or greater than 10.

    Operator precedenceThe precedence of operators in expressions follows:

    This figure includes operators used mainly by individuals experienced inprogramming. See Programming features on page 75 for details.

    In the figure, operators on the same row have equal precedence. If astatement has two or more operators from the same row, the operatorfurthest to the left is evaluated first.

    The parentheses at the top of the figure are for grouping a condition or

    elements of a statement. As shown in a following example, parentheses areuseful for altering the order of operator evaluation.

    ( ) [ ]

    ! ++ - -* / % ^+ -

    < >=== !=&&

    ||= += -= *= /=

    Highest

    Lowest

  • 5/28/2018 Maya -Tutorial (Expressions)

    69/274

    Using Maya: Hypergraph, Sets & Expressions 69

    Expression Syntax

    Conditional statements

    Expr

    essions

    Examples

    Ball.scaleY = 8 + 2 * 4;

    This assigns Ball.scaleY the