【发布时间】:2011-10-28 17:31:18
【问题描述】:
我有一个类tetronimo(一个俄罗斯方块块),它有四个QRect 类型(分别命名为first、second、third、fourth)。我使用build_tetronimo_L 类型函数绘制每个tetronimo。
这些在某个方向上构建了 tetronimo,但就像在俄罗斯方块中你应该能够旋转 tetronimo 一样,我试图通过旋转 tetronimo 的每个单独的正方形来旋转 tetronimo。
我发现以下公式适用于特定正方形的每个 (x, y) 坐标。
newx = cos(angle) * oldx - sin(angle) * oldy
newy = sin(angle) * oldx + cos(angle) * oldy
现在,Qt 的 QRect 类型似乎只有一个 setCoords 函数,它采用 top-left 和 bottom-right 的 (x, y) 坐标 相应正方形的点。
我在这里有一个例子(它似乎不会产生正确的结果)旋转我的 tetronimo 中的前两个方块。
谁能告诉我应该如何使用运行时旋转计算正确旋转这些正方形?
void tetromino::rotate(double angle) // angle in degrees
{
std::map<std::string, rect_coords> coords = get_coordinates();
// FIRST SQUARE
rect_coords first_coords = coords["first"];
//top left x and y
int newx_first_tl = (cos(to_radians(angle)) * first_coords.top_left_x) - (sin(to_radians(angle)) * first_coords.top_left_y);
int newy_first_tl = (sin(to_radians(angle)) * first_coords.top_left_x) + (cos(to_radians(angle)) * first_coords.top_left_y);
//bottom right x and y
int newx_first_bl = (cos(to_radians(angle)) * first_coords.bottom_right_x) - (sin(to_radians(angle)) * first_coords.bottom_right_y);
int newy_first_bl = (cos(to_radians(angle)) * first_coords.bottom_right_x) + (sin(to_radians(angle)) * first_coords.bottom_right_y);
//CHANGE COORDINATES
first->setCoords( newx_first_tl, newy_first_tl, newx_first_tl + tetro_size,newy_first_tl - tetro_size);
//SECOND SQUARE
rect_coords second_coords = coords["second"];
int newx_second_tl = (cos(to_radians(angle)) * second_coords.top_left_x) - (sin(to_radians(angle)) * second_coords.top_left_y);
int newy_second_tl = (sin(to_radians(angle)) * second_coords.top_left_x) + (cos(to_radians(angle)) * second_coords.top_left_y);
//CHANGE COORDINATES
second->setCoords(newx_second_tl, newy_second_tl, newx_second_tl - tetro_size, newy_second_tl + tetro_size);
first 和 second 是 QRect 类型。 rect_coords 只是一个 struct,其中包含四个 ints,用于存储正方形的坐标。
第一个平方和第二个平方的计算是不同的,因为我正在玩弄试图弄明白。
希望有人能帮我解决这个问题?
(是的,我可以做到这一点更简单,但我正在尝试从中学习)
【问题讨论】:
标签: c++ qt graphics rotation coordinates