1
votes

It is stated, that to rotate a line by a certain angle, you multiply its end point coordinates by the matrix ({Cos(a), Sin(a)} {-Sin(a) Cos(a)}), where a is rotation angle. The resulting two numbers in matrix will be x and y coordinates of rotated line's end point. Rotation goes around line's start point. Simplifying it, new coordinates will be {x*Cos(a) - y*Sin(a)} for x and {x*Sin(a) + y*Cos(a)} for y.

Task is to rotate a triangle, using this method. But the following code that uses this method, is giving out some crap instead of rotated image (twisted form of original triangle, rotated by "random" angle):

x0:=200;   
y0:=200;

  bx:=StrToInt(Edit1.Text);
  by:=StrToInt(Edit2.Text);
  cx:=StrToInt(Edit4.Text);
  cy:=StrToInt(Edit5.Text);
  a:=StrToInt(Edit3.Text);

  //Original triangle

  Form1.Canvas.Pen.Color:=clBlue;
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(bx,by);
  Form1.Canvas.LineTo(cx,cy);
  Form1.Canvas.LineTo(x0,y0);

  //New triangle
  Form1.Canvas.Pen.Color:=clGreen;    
  Form1.Canvas.MoveTo(x0,y0);
  b1x:=Round(bx*cos(a*pi/180)-by*sin(a*pi/180));   
  b1y:=Round(bx*sin(a*pi/180)+by*cos(a*pi/180));
  c1x:=Round(cx*cos(a*pi/180)-cy*sin(a*pi/180)); 
  c1y:=Round(cx*sin(a*pi/180)+cy*cos(a*pi/180));
  Form1.Canvas.LineTo(b1x,b1y);
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(c1x,c1y);
  Form1.Canvas.LineTo(b1x,b1y);

end;

Well, I'm out of ideas. What am I doing wrong?

Thanks for your time.

2

2 Answers

4
votes

The formula you are using rotates a point around (0, 0). To achieve the required result change your calculation to:

b1x:=x0 + Round((bx-x0)*cos(a*pi/180)-(by-y0)*sin(a*pi/180));   
b1y:=y0 + Round((bx-x0)*sin(a*pi/180)+(by-y0)*cos(a*pi/180));
c1x:=x0 + Round((cx-x0)*cos(a*pi/180)-(cy-y0)*sin(a*pi/180)); 
c1y:=y0 + Round((cx-x0)*sin(a*pi/180)+(cy-y0)*cos(a*pi/180));
4
votes

You appear to be rotating each individual line round its initial start point coordinates. So line 1 will get rotated about its start point (x0,y0); then line 2 will get rotated about bx,by; then line 3 will get rotated round cx. This will result in a twisted triangle. Instead you will need to rotate all three lines round the start point of the first line.