November 17, 2008
Rotations and reflections are easy enough with the Actionscript 3 Matrix class as long as you want a reflection whose mirror line passes through the origin, or a rotation about the origin.
However I recently was stumped with producing transformation matrices that included rotations about any point and reflection along any line. As there was little example code out there for this, I’ve decided to publish the two methods I’ve written to perform this. Both methods take the Matrix to set the transformation to as the first argument.
/**
* Constructs an affine rotation matrix.
*
* @param m The matrix to set the affine rotation to.
* @param angle The angle of rotation in radian.
* @param ox center of rotation in the x axis
* @param oy center of rotation in the y axis
*
*/
private function rotation(m:Matrix,angle:Number=0,ox:Number=0,oy:Number=0):void
{
m.rotate(angle);
m.tx=ox-(m.a*ox)+(m.b*oy);
m.ty=oy+(m.c*ox)-(m.d*oy);
}
/**
* Constructs an affine reflection matrix. The line of reflection
* is defined by the last three parameters of the method.
* @param m Matrix The matrix to set the affine reflection to.
* @param angle Number The angle of rotation in radians.
* @param ox Number The reflection lines relative position from the origin.
* @param oy Number The reflection lines relative position from the origin.
*
*/
private function reflection(m:Matrix,angle:Number=0,ox:Number=0,oy:Number=0):void
{
m.a= Math.cos(2*angle);
m.b= Math.sin(2*angle);
m.c= Math.sin(2*angle);
m.d= -Math.cos(2*angle);
m.tx=ox-(m.a*ox)+(m.b*oy);
m.ty=oy+(m.c*ox)-(m.d*oy);
}