计算旋转后新的X,Y矩形坐标

问题描述 投票:0回答:1

trigonometry, rotated triangle

如何正确计算矩形旋转30度后的X1?旋转前的X点是164,83。我使用了这段代码:

void rotate_rectangle(double x, double y, double angle, double* new_x, double* new_y) {
  // Convert angle to radians
  double angle_rad = angle * M_PI / 180.0;

  // Calculate coordinates of top-left corner relative to center
  double rel_x = -w / 2;
  double rel_y = -h / 2;

  // Rotate top-left corner around center
  double new_rel_x = rel_x * cos(angle_rad) - rel_y * sin(angle_rad);
  double new_rel_y = rel_x * sin(angle_rad) + rel_y * cos(angle_rad);

  // Calculate new coordinates of top-left corner
  *new_x = x + new_rel_x;
  *new_y = y + new_rel_y;
}

但是从打印输出中可以看到,当鼠标指向 X1 时,坐标为 190,35,但计算结果为 89 和 11。

有人可以分享一些关于这方面的信息吗?遗憾的是,谷歌没有提供帮助。

math geometry trigonometry rotational-matrices
1个回答
0
投票

将原始坐标计算为极坐标,相对于(x+w/2)和(y+h/2)。 IE。你需要得到它相对于你的直角中心的角度和半径。然后更新后的位置使用相同的半径,但角度等于(原始角度 + 旋转角度)。然后您只需要 x=cos(a) 和 y=sin(a):

void rotate_rectangle(double x, double y, double angle, double* new_x, double* new_y) {
  // Get the center offset
  double cx = x + w/2;
  double cy = y + h/2;

  // Get (x,y) as polar coordinate
  double dx = x - w/2;
  double dy = x - w/2;
  double a = atan2(dy, dx);
  double m = sqrt(dx*dx + dy*dy);

  // Then all we need to do is update that angle
  angle = a + angle * M_PI / 180.0;

  // And then we convert back to euclidean:
  *new_x = cx + m * cos(angle);
  *new_y = cy + m * sin(angle);
}
© www.soinside.com 2019 - 2024. All rights reserved.