Reputation: 12854
I have a rectangle on the scene and I want to rotate it with mouse. The rectangle has his own origin point. Clicking on the scene represents start of rotation and mouse moving represent angle of rotation.
where:
so I calculate the angle in next steps:
Fistly, I get lengths of triangle sides:
AO = sqrt( (O.x - A.x)^2 + (O.y - A.y)^2 ) CO = sqrt( (O.x - C.x)^2 + (O.y - C.y)^2 ) AC = sqrt( (C.x - A.x)^2 + (C.y - A.y)^2 )
and then I calculate the angle (a):
a = arccos ( (AO^2 + CO^2 - AC^2) / (2 * AO * CO) )
it works, but this calculation look too complicated taking into account that I need to repeat on it all OnMouseMove call.
So my question - is there another way to calculate the angle? I write it in c++ so some code snippet will be apprecated.
Upvotes: 0
Views: 1613
Reputation: 4992
You use a dot product of vectors OA and OC divided by their magnitude to calculate cosine of the angle and then use acos()
function to find the angle.
float cosAngle = (x1 * x2 + y1 * y2) / sqrt(x1*x1 + y1*y1) * sqrt(x2*x2 + y2*y2);
float angle = acos(cosAngle);
Upvotes: 1
Reputation: 80107
You can find angle between vectors OA and OC through their scalar product and cross product:
OA = (OA.X, OA.Y) = (A.X-O.X, A.Y-O.Y)
OC = (OC.X, OC.Y) = (C.X-O.X, C.Y-O.Y)
SP = OA * OC = OA.X*OC.X+OA.Y*OC.Y
CP = OA x OC = OA.X*OC.Y-OA.Y*OC.X
Angle = atan2(CP, SP)
Example: O = (0,0), A = (-1, 0), C = (-2, 1) SP = 2, CP = -1, Angle = -0.463
This method allows to avoid sqrt calculations, and determines rotation direction (unlike arccos)
Upvotes: 2