我有一個要旋轉的三角形(在 2D 平面上)。我計算了它的質心,現在我有一個中心(質心)的假想圓,指向 0 度角(三角形的第一個頂點)。我的想法是通過增加它的角度(在回圈上)并為該角度的頂點找到新坐標來旋轉每個頂點。
#include <stdio.h>
#include <math.h>
//"the function"
int calculate_new_vertex_for_trangle(int center_x, int center_y,int x_at_0,int y_at_0,int angle)
{
double radius = sqrt(pow(x_at_0-center_x,2) pow(y_at_0-center_y,2));
float angle_to_radian = ((22.0/7.0)/180)*angle;
// googled formula
float new_x = center_x radius*cos(angle_to_radian);
float new_y = center_y radius*sin(angle_to_radian);
printf("x : %f, y : %f \nradius : %f\n", new_x, new_y,radius);
return 0;
}
預期產出
但我得到的結果是:圖片
行尾的數字是我使用“函式”得到的各個角度的坐標位置。
uj5u.com熱心網友回復:
這個公式:
float new_x = center_x radius*cos(angle_to_radian);
float new_y = center_y radius*sin(angle_to_radian);
在圍繞 (center_x, center_y) 逆時針旋轉后,給出頂點在 angle=0 處的新位置. 但是你想要任何頂點的新位置。
您可以計算 處的點的初始角度(逆時針)(px,py):
float angle_ini = atan2(px-center_x, py-center_y);
然后將其用于旋轉位置:
float new_x = center_x radius*cos(angle_to_radian angle_ini);
float new_y = center_y radius*sin(angle_to_radian angle_ini);
還有第二個公式可以達到相同的結果,稱為“旋轉變換”
float angle_to_radian = (3.14159265358979/180)*angle;
float sinA = sin(angle_to_radian);
float cosA = cos(angle_to_radian);
float new_x = center_x (px-center_x)*cosA - (py-center_y)*sinA;
float new_y = center_y (px-center_x)*sinA (py-center_y)*cosA;
請注意,使用第二種方法可以避免計算半徑。
uj5u.com熱心網友回復:
我認為,圍繞另一個點旋轉一個點的好方法是使用旋轉矩陣。您可以在 Wikipedia 上找到更多詳細資訊: https ://en.wikipedia.org/wiki/Rotation_matrix
我希望這個示例代碼對您有所幫助:
#include <stdio.h>
#include <math.h>
int main()
{
// Center on circle
float center_x = 0.0;
float center_y = 0.0;
// Point on circle
float point_x = 1.0;
float point_y = 1.0;
// Rotation angle
float rotation_deg = 180;
float rotation_rad = rotation_deg * M_PI / 180.0;
// Rotation matrix
float a = cos(rotation_rad);
float b = -sin(rotation_rad);
float c = sin(rotation_rad);
float d = cos(rotation_rad);
// Matrix multiplication
float dx = point_x - center_x;
float dy = point_y - center_y;
float new_x = a * dx b * dy;
float new_y = c * dx d * dy;
// Add center point
new_x = center_x;
new_y = center_y;
printf("old_point = %.2f|%.2f\n", point_x, point_y);
printf("new_point = %.2f|%.2f\n", new_x, new_y);
}
問候。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/504165.html
上一篇:計算達到一定勝率所需的勝數?
