如何围绕中心旋转90度的线段?

时间:2017-08-15 21:11:33

标签: algorithm

由于我对数学非常不理解并且不理解this paper on the topic的单词,并且this answer I found对我来说没有足够的解释,有人可以展示我用伪代码的算法来旋转一个线段,比如说(50,40) - (50,120)围绕它的中心点(90度)?真的很感激。

2 个答案:

答案 0 :(得分:5)

90度是一个简单的特例。假设您有一行(x1,y1)(x2,y2)

//find the center
cx = (x1+x2)/2;
cy = (y1+y2)/2;

//move the line to center on the origin
x1-=cx; y1-=cy;
x2-=cx; y2-=cy;

//rotate both points
xtemp = x1; ytemp = y1;
x1=-ytemp; y1=xtemp; 

xtemp = x2; ytemp = y2;
x2=-ytemp; y2=xtemp; 

//move the center point back to where it was
x1+=cx; y1+=cy;
x2+=cx; y2+=cy;

答案 1 :(得分:1)

对于线段,您可以使用类似这样的函数:

function rotate(a, b, angle) {
    // a and b are arrays of length 2 with the x, y coordinate of
    // your segments extreme points with the form [x, y]

    midpoint = [
        (a[0] + b[0])/2,
        (a[1] + b[1])/2
    ]

    // Make the midpoint the origin
    a_mid = [
        a[0] - midpoint[0],
        a[1] - midpoint[1]
    ]
    b_mid = [
        b[0] - midpoint[0],
        b[1] - midpoint[1]
    ]

    // Use the rotation matrix from the paper you mentioned
    a_rotated = [
        cos(angle)*a_mid[0] - sin(angle)*a_mid[1],
        sin(angle)*a_mid[0] + cos(angle)*a_mid[1]
    ]
    b_rotated = [
        cos(angle)*b_mid[0] - sin(angle)*b_mid[1],
        sin(angle)*b_mid[0] + cos(angle)*b_mid[1]
    ]

    // Then add the midpoint coordinates to return to previous origin
    a_rotated[0] = a_rotated[0] + midpoint[0]
    a_rotated[1] = a_rotated[1] + midpoint[1]
    b_rotated[0] = b_rotated[0] + midpoint[0]
    b_rotated[1] = b_rotated[1] + midpoint[1]

    // And the rotation is now done
    return [a_rotated, b_rotated]
}

你将如何使用它:

// In your case:
a = [50, 40]
b = [50, 120]
angle_degrees = 90
angle_radians = angle_degrees*pi/180

rotated = rotate(a, b, angle_radians)
// Rotated[0] will be your new a coordinates, in your case [90, 80]
// Rotated[1] will be your new b coordinates, in your case [10, 80]