Home > Backend Development > C++ > How Do You Rotate a Point Around Another Point in 2D Space?

How Do You Rotate a Point Around Another Point in 2D Space?

Patricia Arquette
Release: 2024-12-07 15:58:11
Original
899 people have browsed it

How Do You Rotate a Point Around Another Point in 2D Space?

Rotating a Point around Another Point in Two Dimensions

This article addresses the challenge of calculating the rotation of a point around another point in two dimensions. The task arises in the development of a card game where cards are fanned out. Allegro API's al_draw_rotated_bitmap function facilitates easy card fanning, but it hinders mouse interaction by obscuring the cards underneath. To address this, a polygon collision test is proposed, which requires the rotation of the card's four points.

The solution lies in utilizing a rotation function that performs the following operations:

  1. Subtract the pivot point from the point's coordinates.
  2. Rotate the point counterclockwise.
  3. Add the pivot point back to the point's coordinates.

This function, rotate_point, is implemented as follows:

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;
}
Copy after login

By implementing this function, the four points of the card can be rotated to determine which card is beneath the mouse, enabling effective mouse interaction in the card game.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template