2017-08-15 3 views
1

Da ich wirklich schlecht mit Mathe bin und kein Wort von this paper on the topic verstehe, und this answer I found es nicht klar genug für mich erklärt, könnte mir jemand den Algorithmus im Pseudocode zeigen, um ein Liniensegment zu drehen, sagen wir um (50,40) - (50,120) um seinen Mittelpunkt herum (um 90 Grad)? Würde es wirklich zu schätzen wissen.Wie kann ich ein Liniensegment um seine Mitte um 90 Grad drehen?

+0

Wikipedia hat ein Beispiel für die Verwendung einer Rotationsmatrix: https://en.wikipedia.org/wiki/Rotation_matrix#In_two_dimensions – user3080953

Antwort

5

90 Grad ist ein einfacher Sonderfall. Nehmen wir an Sie eine Linie (x1,y1)-(x2,y2) haben:

//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

@Viziionary: Sie müssen wirklich keine Forschungsarbeit lesen, um eine Linie zu drehen 90 Grad. Diese Antwort ist der einfachste Weg. Die einzige Verbesserung ist, dass "cx" und "cy" auch entfernt werden, indem ihre Werte überall direkt ersetzt werden. – displayName

1

Für ein Liniensegment, eine Funktion wie diese verwenden:

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

Wie würden Sie es verwenden:

// 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] 
+0

Könnte für den speziellen Fall von 90 ° einfacher sein als von @MattTimmermans gezeigt, aber definitiv auch eine sehr nützliche Antwort. Ich mag es, dass du die Technik des erwähnten Papiers OP benutzt und es mit Kommentaren erklärt hast. – Zabuza

Verwandte Themen