You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确计算矩形旋转30度后的X1坐标?计算结果不符

矩形旋转后坐标计算问题

trigonometry, rotated triangle

问题说明

旋转前矩形左上角(X1)坐标为(164,83),将矩形旋转30度后,实际显示的X1坐标为(190,35),但使用以下C代码计算得到的结果却是(89,11),需要修正代码逻辑:

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

问题根源及修正方案

1. 坐标基准错误

代码假设传入的x,y是矩形的中心坐标,但实际传入的是旋转前左上角(X1)的坐标(164,83),这会导致偏移计算完全错误。

2. 图形坐标系方向差异

多数图形系统(如UI、游戏引擎)的y轴是向下的,而标准数学旋转公式基于y轴向上的坐标系,这会导致旋转方向和y坐标计算反向。

3. 修正后的代码

假设w和h是矩形的宽和高,以下是修正后的逻辑:

#include <math.h>

void rotate_rectangle(double orig_x, double orig_y, double w, double h, double angle, double* new_x, double* new_y) {
    // 1. 计算原矩形的中心坐标(旋转绕中心进行)
    double center_x = orig_x + w / 2.0;
    double center_y = orig_y + h / 2.0;

    // 2. 计算左上角相对于中心的偏移
    double rel_x = orig_x - center_x;
    double rel_y = orig_y - center_y;

    // 3. 角度转弧度,适配y轴向下的图形系统(顺时针旋转)
    double angle_rad = angle * M_PI / 180.0;
    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);

    // 4. 计算旋转后的左上角坐标
    *new_x = center_x + new_rel_x;
    *new_y = center_y + new_rel_y;
}

额外说明

  • 若系统坐标系y轴向上,或需要逆时针旋转,使用标准数学旋转公式:
    new_rel_x = rel_x * cosθ - rel_y * sinθ;
    new_rel_y = rel_x * sinθ + rel_y * cosθ;
    
  • 确保w和h为矩形真实宽高,否则偏移计算会出错。

内容的提问来源于stack exchange,提问作者GiuTor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:57:04