Reputation: 127
I've been scratching my head over this problem for the past few days, and I just can't come up with a working (let alone efficient) solution.
I have a set of points in an array, representing a mouse path:
Points[0] = 20,50
Points[Points.length-1] = 500,230
Im trying to find a way to rotate the array of points (Path) so that the first point begins at x1,y1 and the last point ends at x2,y2.
I know that this will involve scaling and rotating the entire array but having lacking knowledge in math, I have no idea on how to approach this.
Any ideas? Thank you!
Upvotes: 1
Views: 596
Reputation: 24427
As James Large says in a comment, you can do this efficiently using a transform matrix. Your transformation is going to require scaling, rotation and translation, each of which can be represented with a matrix, and you can build a single transformation matrix that does all this at once out of simpler transformations just by multiplying the the matrices representing each transform together using matrix multiplication.
You can achieve what you want by first translating the points so that the first point is at the origin (because that's the point you want to rotate around), then applying a rotation, a scaling transform and then a second translation so that the first point is at x1, y1.
The rotation angle can be calculated by computing the difference between the angle between (x1, y1) - (x2, y2) and the angle between the original start and end points:
double rotationAngle = atan2(y2-y1, x2-x1) -
atan2(Points[Points.length-1].y-Points[0].y, Points[Points.length-1].x-Points[0].x);
The scaling factor is the distance between (x1, y1) - (x2, y2) divided by the distance between the untransformed start and end points.
So your transformation can be built like this:
The order of rotation and scaling could be swapped, it doesn't matter. See the article of transformation matrices for how to build each one.
You could also solve using simultaneous equations, but I think this way is more intuitive. You'll end up with the same matrix so the per-point transformation is just as efficient.
Upvotes: 1