我需要实现一个2d形状的旋转功能

时间:2011-12-01 03:11:50

标签: c++

这是公式,但我不知道如何实现它。有人可以帮忙吗

enter image description here

enter image description here

rectangle::rectangle()  //rectangle constructor
{
    bl.real() = 0; //bottom
    bl.imag() = 0; //left

    tr.real() = 1; //top
    tr.imag() = 1; //right
}

complex<double> rectangle::get_bl() const
{
    return bl;
}

complex<double> rectangle::get_tr() const
{
    return tr;
}

void rectangle::rotate(double angle)
{
    //not sure how to do it  tr = tr.real() * cos(angle) + tr.imag() *cos(angle);


}

rectangle r;
r.rotate(90);

预期产出(不是100%肯定)

0 0 -1 1

2 个答案:

答案 0 :(得分:2)

  1. 暂时将您的形状移动到(0, 0)(公式假设您正在围绕原点旋转,因此将左下角移动到(0, 0))。
  2. 申请公式。
  3. 将其移回。

  4. if (tr.real() < bl.real()) {
      float tempX = tr.real() - bl.real();
      float tempY = tr.imag() - bl.imag();
    } else {
      float tempX = bl.real() - tr.real();
      float tempY = bl.imag() - tr.imag();
    }
    
    tr.real() = tempX * cos(theta) - tempY * sin(theta)
    tr.imag() = tempx * sin(theta) + tempY * cos(theta)
    

答案 1 :(得分:0)

该公式基本上是这样说:

new_x = shape.point[i].x*cos(angle) - shape.point[i].y*sin(angle)
new_y = shape.point[i].x*sin(angle) + shape.point[i].y*cos(angle)
shape.point[i].x = new_x
shape.point[i].y = new_y

角度是弧度,从度数转换为弧度使用
degree*pi/180其中pi是常量3.14...

您需要对形状上的每个点执行此操作,以使形状完全旋转所需的度数。

此公式还假设点以(0,0)为中心,即形状的中心为(0,0),所有点都相对于该中心。


如果适用,请尝试将形状存储为点,从0th点顺时针方向移动。例如,这个矩形将是:

point[0] = {-1, 1}
point[1] = { 1, 1}
point[2] = { 1,-1}
point[3] = {-1,-1}

要从tl, br转换为points,您需要执行以下操作:

point[0] = {tl.x, tl.y}
point[1] = {br.x, tl.y}
point[2] = {br.x, br.y}
point[3] = {tl.x, br.y}
相关问题