Friday, April 17, 2015

javascript - Matrix rotation of a rectangle to "face" a given point in 2d



Suppose you have a rectangle centered at point (0, 0) and now I want to rotate it such that it is facing the point (100, 100), how would I do this purely with matrix math?


To give some more specifics I am using javascript and canvas and I may have something like this:


var position = {x : 0, y: 0 };
var destination = { x : 100, y: 100 };
var transform = Matrix.identity();

this.update = function(state) {

// update transform to rotate to face destination


};

this.draw = function(ctx) {
ctx.save();
ctx.transform(transform); // a helper that just calls setTransform()
ctx.beginPath();
ctx.rect(-5, -5, 10, 10);
ctx.fillStyle = 'Blue';
ctx.fill();
ctx.lineWidth = 2;

ctx.stroke();
ctx.restore();
}

Feel free to assume any matrix function you need is available.



Answer



Here's my first take on it:


Assuming you want the top edge of the rectangle to be the edge that sets the "facing direction" as per your comment, and that would be considered your identity direction (0, -1) or zero angle in 'JustinSpace', rotating the rect so that that edge faces 100,100 would in effect be a 135 degree rotation clockwise. Most Math libraries think of 1,0 as being the identity direction (or 0 angle) requiring a 90 deg shift of the angle to place it into 'JustinSpace'.


A matrix that rotates something 135 deg clockwise on a 2d XY plane looks like this:


float angle = Math.Atan2(100,100) + Math.Atan2(-1, 0); // 45 deg + 90 deg


//RH coordinate Row Major system
Matrix m = Matrix.Identity();
m.11 = m.22 = cos(angle);
m.12 = sin(angle);
m.21 = -sin(angle);

//for column major
//m.Transpose()


If eBusiness' answer works however, I would use it as linear algebra is almost always favorable over trig in game dev.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...