Home >Backend Development >C++ >How to Rotate a Point Around Another Point in 2D Using Allegro?

How to Rotate a Point Around Another Point in 2D Using Allegro?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 17:26:20970browse

How to Rotate a Point Around Another Point in 2D Using Allegro?

Rotating a Point About Another Point in 2D

In computer graphics, rotating an object around a specific point is a common operation. In this case, you're aiming to rotate the 4 corner points of a card using the Allegro API. To achieve this, consider the following approach:

旋转点函数

You can implement a function called rotate_point to perform the rotation operation in the desired manner. It takes the following parameters:

  • cx and cy: X and Y coordinates of the pivot point
  • angleInRads: Angle of rotation in radians
  • p: The point to be rotated

Implementation:

The rotate_point function first subtracts the pivot point from the given point p. This shifts the point to the origin of the coordinate system. Next, it performs the rotation using the sine and cosine of the rotation angle. Finally, it adds back the pivot point to get the rotated point.

Code:

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;
}

By applying this rotation to the 4 corner points of the card, you can create a rotated polygon that can be used for collision detection.

The above is the detailed content of How to Rotate a Point Around Another Point in 2D Using Allegro?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn