Close

Getting a rotation matrix

A project log for Silly software wishlist

Motivation to do some software projects by writing them down.

lion-mclionheadlion mclionhead 01/27/2020 at 19:160 Comments

One of the greatest functions ever written is the rotation matrix calculator or affine transformation. Pass it a direction vector for the Y axis to point in. It's hard coded for the Z axis to point up. Then, merely multiplying the rotation matrix by any coordinate makes the coordinate relative to the direction vector. All those highschool trig calculations & polar conversions are reduced to a matrix multiplication.

python code:

def vecToRot(direction):
direction = direction.normalized()
up = Vector([0, 0, 1])
xaxis = up.cross(direction)
xaxis = xaxis.normalized()

yaxis = direction.cross(xaxis)
yaxis = yaxis.normalized()

result = Matrix((
(xaxis.x, yaxis.x, direction.x), 
(xaxis.y, yaxis.y, direction.y), 
(xaxis.z, yaxis.z, direction.z)))
return result

usage to rotate an x,y,z coordinate 45 deg:
mat_rot = vecToRot(Vector([1, 1, 0]))
rotated_coord = mat_rot * Vector(x, y, z)

Discussions