I am struggling with the rotation of a triangle derived from a UIRotationGestureRecognizer. If you could take a look at my approach and offer suggestions, I would really appreciate it.
I ask the object of recognition of a gesture for rotation, which is mentioned in the documentation, in radians.
My strategy was to think of each vertex as a point in the circle that exists between the center of the triangle and the vertex, and then use the radian of rotation to find a new point on this circle. I’m not entirely sure that this is the right approach, but I would like to at least give it a try. Visually, I know if it works or not.
Here is the code I created in this attempt:
- (CGPoint)rotateVertex:(CGPoint)vertex byRadians:(float)radians { float deltaX = center.x - vertex.x; float deltaY = center.y - vertex.y; float currentAngle = atanf( deltaX / deltaY ); float newAngle = currentAngle + radians; float newX = cosf(newAngle) + vertex.x; float newY = sinf(newAngle) + vertex.y; return CGPointMake(newX, newY); }
When executing at the beginning, there is a slight rotation, but then, as I continue to rotate my fingers, the vertices only begin to move away from the center point, indicating that I am confusing something here.
I looked at what CGContextRotateCTM can do for me, but in the end I need to know which vertices are after rotation, so just rotating the graphics context does not leave me with these changed coordinates.
I also tried the method described here , but this led to the triangle flipping around the second vertex, which seems odd, but then this technique works with p and q, which are the x and y coordinates of the second vertex.
Thanks for watching!
Solved: Here is the corrected function. It is assumed that you calculated the center of the triangle. I used the 1/3 (x1 + x2 + x3), 1/3 (y1 + y2 + y3) method described in the Wikipedia article on centroids.
- (CGPoint)rotatePoint:(CGPoint)currentPoint byRadians:(float)radiansOfRotation { float deltaX = currentPoint.x - center.x; float deltaY = currentPoint.y - center.y; float radius = sqrtf(powf(deltaX, 2.0) + powf(deltaY, 2.0)); float currentAngle = atan2f( deltaY, deltaX ); float newAngle = currentAngle + radiansOfRotation; float newRun = radius * cosf(newAngle); float newX = center.x + newRun; float newRise = radius * sinf(newAngle); float newY = center.y + newRise; return CGPointMake(newX, newY); }
It is noteworthy why the first code did not work, that the atan2 arguments were canceled. In addition, the correct calculation of delta values was canceled.