Friday, April 24, 2009

How to Set an Object's Rotation in Maxscript

It is very surprising to me how hard it is sometimes to Google solutions for what should be simple/common problems in Maxscript. This ends up being one of the largest time sinks I encounter at work. After running into this problem yet again today, I decided to start posting solutions to these problems when I run into them. Today I needed to figure out how to set the x, y, and z rotation values for an object. Google was no help. The Maxscript documentation isn't much better. Here is the relatively simple solution I arrived at:

------------------------------------------------------
-- Set the given object's rotation to the given values
------------------------------------------------------
fn SetObjectRotation obj rx ry rz =
(
-- Reset the object's transformation matrix so that
-- it only includes position and scale information.
-- Doing this clears out any previous object rotation.
local translateMat = transMatrix obj.transform.pos
local scaleMat = scaleMatrix obj.transform.scale
obj.transform = scaleMat * translateMat

-- Perform each axis rotation individually
rotate obj (angleaxis rx [1,0,0])
rotate obj (angleaxis ry [0,1,0])
rotate obj (angleaxis rz [0,0,1])
)

-- Set currently selected Object's rotation to 80 50 100
SetObjectRotation selection[1] 80 50 100


As with anything in Maxscript, there are probably several solutions to this problem. This one works great for me.

2 comments:

Sterling & Laura said...

Thank you for this. It was one stop shopping to solve my problem.

Anonymous said...

This is an elegant solution - thanks very much