Purp
Purp

Reputation: 131

Get the direction an object's axis is pointing in Maya

Using python I'm trying to confirm that a given transform node in Maya has it's Y axis pointing up, Z axis pointing forward, and X axis pointing to the side, like in the picture below. The transform node might be a child to another transform node in a hierarchy of unknown depth.

My first thought was to use xform rotate pivot matrix? I'm not sure if this is the correct thing or how to interpret the matrix values.

enter image description here

Upvotes: 2

Views: 4010

Answers (2)

m3trik
m3trik

Reputation: 333

I wrapped @theodox answer into a function. Maybe it will be helpful to someone in the future.

def getOrientation(obj, returnType='point'):
    '''
    Get an objects orientation.

    args:
        obj (str)(obj) = The object to get the orientation of.
        returnType (str) = The desired returned value type. (valid: 'point', 'vector')(default: 'point')

    returns:
        (tuple)
    '''
    obj = pm.ls(obj)[0]

    world_matrix = pm.xform(obj, q=True, m=True, ws=True)
    rAxis = pm.getAttr(obj.rotateAxis)
    if any((rAxis[0], rAxis[1], rAxis[2])):
        print('# Warning: {} has a modified .rotateAxis of {} which is included in the result. #'.format(obj, rAxis))

    if returnType is 'vector':
        from maya.api.OpenMaya import MVector

        result = (
            MVector(world_matrix[0:3]),
            MVector(world_matrix[4:7]),
            MVector(world_matrix[8:11])
        )

    else:
        result = (
            world_matrix[0:3],
            world_matrix[4:7],
            world_matrix[8:11]
        )


    return result

Upvotes: 0

theodox
theodox

Reputation: 12218

For most objects, you can get the orientation in world space quite simply:

import maya.cmds as cmds

world_mat = cmds.xform(my_object, q=True, m=True, ws=True)
x_axis = world_mat[0:3]
y_axis = world_mat[4:7]
z_axis = world_mat[8:11]

If you want them in vector form (so you can normalize them or dot them) you can use the maya api to get them as vectors. So for example

import maya.cmds as cmds
import maya.api.OpenMaya as api

my_object = 'pCube1'
world_mat = cmds.xform(my_object, q=True, m=True, ws=True)
x_axis = api.MVector(world_mat[0:3])
y_axis = api.MVector(world_mat[4:7])
z_axis = api.MVector(world_mat[8:11])

# 1 = straight up, 0 = 90 degrees from up, -1 = straight down
y_up = y_axis * api.MVector(0,1,0)

This will include the any modifications that might have been made to the .rotateAxis parameter on the object so it's not guaranteed to line up with the visual tripod if that's been manipulated.

If you don't have reason to expect the .rotateAxis has been set, this the easiest way to do it. A good intermediate step would be just to warn on objects that have a non-zero .rotateAxis so there is no ambiguity in the results, it might be unclear what the correct course of action there is in any case.

Upvotes: 5

Related Questions