Home > Delphi > Rotate a polygon

## Rotate a polygon

One of the benefits of writing an RTL from scratch is that you get the chance to wake up old gems from the past. For instance, how do you rotate a polygon (array of TPoints) around a variable axis? While my work at the office is extremely serious, I must admit that playing around with these routines is very entertaining.

Note: The example below is just one way of doing things. As a friend of mine pointed out, it would be considerably faster to use a matrix / linear approach.

While this example is for Smart Mobile Studio‘s flavour of object pascal, it should be fairly easy to get it running under vanilla Delphi or freepascal. Enjoy the retro feeling 🙂

```type
TPointArray = array of TPoint;

function Rotate(const angle:Float;
const aValues:TPointArray;
const centerX,centerY:Float):TPointArray;
var
i:    integer;
r,p:  Float;
begin
if aValues.Length>0 then
Begin
result.SetLength(aValues.Length);
for i := 0 to aValues.length-1 do
begin
r:=sqrt(sqr(aValues[i].X - centerX) + sqr(aValues[i].Y - centerY));
p := angle + arcTan2(aValues[i].Y - centerY, aValues[i].X - centerX);
Result[i].X := Round(centerX + r * cos(p));
Result[i].Y := Round(centerY + r * sin(p));
end;
end;
end;
```

Here is one way of using it:

```  (* setup our array of points *)
mItems.SetLength(0);

(* do the mambo *)
mItems:=rotate(fbValue,mItems,gameview.width div 2,gameview.height div 2);

(* Paint on our HTML5 canvas *)
Canvas.MoveToF(mItems.x,mItems.y);
for i:=1 to mItems.high do
canvas.linetoF(mItems[i].x,mItems[i].y);
canvas.linetoF(mItems.x,mItems.y);
```

And the end result (the cube rotates around the screen):

Here is a buffer we prepared earlier, using the numbers of life: