Coding for Fun: Matrix Transform with Rotation Matrix Transforms
-
Very important matrix transformations for managing 3D object directions.
function matrix_transform(vec, mat) // matrices are defined here as an array of row vectors // i.e., [{1,0,0}, {0,1,0}, {0,0,1}] for a 3x3 identity vector v = {} for i=0 to len(mat) loop v[i] = dot(mat[i], vec) repeat return v function rotation_matX(rx) // make a rotation matrix for the x axis var xc = cos(rx) var xs = sin(rx) var rmx = [{1,0,0}, {0,xc,-xs}, {0, xs, xc}] return rmx function rotation_matY(ry) // make a rotation matrix for the y axis var yc = cos(ry) var ys = cos(ry) var rmy = [{yc,0,ys}, {0,1,0}, {-ys,0,yc}] return rmy function rotation_matZ(rz) // make a rotation matrix for the z axis var zc = cos(rz) var zs = sin(rz) var rmz = [{zc, -zs, 0}, {zs, zc, 0}, {0,0,1}] return rmz function rotateX(direction, degrees) vector new_dir = matrix_transform(direction, rotation_matX(degrees)) return new_dir function rotateZ(direction, degrees) vector new_dir = matrix_transform(direction, rotation_matZ(degrees)) return new_dir function rotateY(direction, degrees) // best one! rotate around Up vector new_dir = matrix_transform(direction, rotation_matY(degrees)) return new_dir function rotate(direction, rot) // direction is a normal vector that specifies // facing (i.e., to use with objectPointAt) // rot is a vector of x, y, and z values var new_dir = direction // order of operations is important, I just like this order new_dir = rotateY(new_dir, rot.y) new_dir = rotateZ(new_dir, rot.z) new_dir = rotateX(new_dir, rot.x) return new_dir vector forward = {0,0,1} function setObjectDirection(obj, pos, rot) // rot is a vector with the degrees for rotation on // each axis, applied in y,z,x order vector new_dir = rotate(forward, rot) setObjectPos(obj, pos) objectPointAt(obj, pos+new_dir) return void
Forgot to add: Thanks for reading!
Jason -
Do you have an ID code for this?
-
@monkeee There is similar code in the 3D collision detection project. Each rotation function above gives a rotation matrix, but in the collision detection project, under the function rotate(), those matrices are defined as rmx, rmy, and rmz. The ID for that one is 5E1R7MND5.
-
I don’t understand what this does! :S