# Matrix rotation problem in 2d

This topic is 2161 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm sure this is something really stupid but I'm drawing a blank on it. I'm just playing about with some basic 2d transformations in javascript. Translations and scaling are working perfectly but rotation has gone a bit weird. I'm sure many of you will probably be able to tell what's wrong just by seeing the rotation movement so I have uploaded a demo to here:

http://x2k.co.uk/canvastest/2d.html

All the code is obviously visible via view src but here are the relevant bits:

 Matrix.init = function() { this.data = [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; }

 Matrix.setRotate = function(r) { this.init(); this.data[0][0] = Math.cos(r); this.data[0][1] = Math.sin(r); this.data[1][0] = -Math.sin(r); this.data[1][1] = Math.cos(r); return this; }

 Vector.transform = function(matrix) { this.x = (this.x * matrix.data[0][0] + this.y * matrix.data[1][0] + matrix.data[2][0]); this.y = (this.x * matrix.data[0][1] + this.y * matrix.data[1][1] + matrix.data[2][1]); return this; }

Like I said I'm sure it's something really simple but I've been trying to work it out and failing so I'd very much appreciate it if one of you guys could point me in the right direction.

Many thanks!!!

##### Share on other sites
I cant see anything really wrong with the math so Im guessing its a javascript value passing/usage problem.
Try taking a single point say (1.0, 0.0) and apply a series of 45 or 90 degree rotations to it so it moves like the hands of a clock, print the values and make sure they are landing at (0.0, 1.0), (-1.0, 0.0), (0.0, -1..0), etc

##### Share on other sites
Got it, was a case of being a total idiot (as I suspected)

this is wrong because it changes the value of y before which causes the second calculation to be incorrect

 Vector.transform = function(matrix) { this.x = (this.x * matrix.data[0][0] + this.y * matrix.data[1][0] + matrix.data[2][0]); this.y = (this.x * matrix.data[0][1] + this.y * matrix.data[1][1] + matrix.data[2][1]); return this; }

changed it to
 Vector.transform = function(matrix) { x = (this.x * matrix.data[0][0] + this.y * matrix.data[1][0] + matrix.data[2][0]); y = (this.x * matrix.data[0][1] + this.y * matrix.data[1][1] + matrix.data[2][1]); this.x = x; this.y = y; return this; }