Home >Backend Development >C++ >How Do I Rotate a Point Around a Fixed Point in 2D?
Rotating Points About a Fixed Point in 2D
In order to create a realistic card-fanning effect in a card game, it is necessary to transform the coordinates of the card points to align with the rotation angle. The Allegro API provides a convenient function for rotating bitmaps, but understanding the underlying mathematical operations is crucial for collision detection purposes.
Rotation Transformation Algorithm
To rotate a point (x, y) about a fixed point (cx, cy) by an angle θ, follow these steps:
Subtract the Pivot Point: Subtract the x and y coordinates of the pivot point from the coordinates of the point to be rotated:
dx = x - cx dy = y - cy
Apply Rotation Matrix: Apply the rotation matrix to rotate the point by angle θ:
x_new = dx * cos(θ) - dy * sin(θ) y_new = dx * sin(θ) + dy * cos(θ)
Add the Pivot Point Back: Add the x and y coordinates of the pivot point back to the transformed coordinates:
x = x_new + cx y = y_new + cy
Implementation
Using this algorithm, here is a C-like function to perform the rotation:
POINT rotate_point(float cx, float cy, float angleInRads, POINT p) { float s = sin(angleInRads); float c = cos(angleInRads); // Translate point back to origin: p.x -= cx; p.y -= cy; // Rotate point float xnew = p.x * c - p.y * s; float ynew = p.x * s + p.y * c; // Translate point back: p.x = xnew + cx; p.y = ynew + cy; return p; }
Using this function, you can now rotate the points of the card to perform the collision detection for the mouse click events.
The above is the detailed content of How Do I Rotate a Point Around a Fixed Point in 2D?. For more information, please follow other related articles on the PHP Chinese website!