# Polygon

Autocad has a polygon command, but it does not have a polygon object. An object created with the polygon command lists as a polyline. So there is no polygon object in VBA to use. We can program a polygon to use variable number of sides and radial length (distance from center to vertex). Dixon has a good algorithm in his book. This version is started from his method and adds variable number of sides and size. It could be more compact but I expanded the code to make it easier to understand.

The center is located with polar coordinates, then the vertexes are saved to an array. The polygon is rotated from the radial center angle, making it ideal for use with spiral routines.

```
Sub to_polygon()
'sample to show usage
Dim n As Integer 'number of sides
Dim Rv As Double ' radial length to vertex
Dim R As Double  'polar distance of center
Dim A As Double  'polar angle of center in degrees

n = 6
Rv = 4
R = 10
A = 45

Call polygon(n, Rv, R, A)
End Sub

Sub polygon(n As Integer, Rv As Double, R As Double, A As Double)
' R A are polar coordinates of the center, A is in degrees
' n is number of sides
' Rv is the radial distance from center to vertex
Call connect_acad

Dim i As Integer
Dim X As Double, Y As Double
' Av is the calculated angle to each vertex from horizontal
Dim Av As Double
Dim A_rad As Double, Av_rad As Double
'center of polygon
Dim Xc As Double, Yc As Double
Dim pt_n() As Double
ReDim pt_n(1 To n * 2)

'the center is given and can be converted to xy immediately
A_rad = deg2rad(A)
Xc = R * Cos(A_rad)
Yc = R * Sin(A_rad)
Debug.Print "polygon center with " & n & " sides"
Debug.Print Xc & " , " & Yc

For i = 1 To n
Av = A + i * (360 / n)
Av_rad = deg2rad(Av)

'X and Y are the vertex locations
X = Rv * Cos(Av_rad) + Xc
Y = Rv * Sin(Av_rad) + Yc

Debug.Print i & ", @ " & Rv & " < " & Av
Debug.Print X & " , " & Y

pt_n(i * 2 - 1) = X: pt_n(i * 2) = Y
Next i

Dim plineobj As AcadLWPolyline
Set plineobj = acadDoc.ModelSpace.AddLightWeightPolyline(pt_n)
plineobj.Closed = True

Update
End Sub

```

polygon center with 6 sides
7.07106781186511 , 7.07106781186584

1, @ 4 < 105
6.03579163145456 , 10.934771117022

2, @ 4 < 165
3.20736450670864 , 8.10634399227519

3, @ 4 < 225
4.24264068711965 , 4.24264068711892

4, @ 4 < 285
8.10634399227646 , 3.20736450670991

5, @ 4 < 345
10.9347711170218 , 6.03579163145729

6, @ 4 < 405
9.89949493660998 , 9.89949493661335

Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.