2D polygon generation

Blitz3D Forums/Blitz3D Beginners Area/2D polygon generation

That is a strange and not very good way to do the loop. what if you want say 37 sides ?

How about this:

Const ScreenWidth = 640
Const ScreenHeight = 480

Const CentreX = ScreenWidth / 2
Const CentreY = ScreenHeight / 2

Graphics ScreenWidth, ScreenHeight, 16, 2
AutoMidHandle(True)
Sides = 3

Print "Press mouse button to change polygons......"
WaitMouse

While True
	If KeyHit(1)
		Exit
	EndIf
		
	X = MouseX() - CentreX 
	Y = MouseY() - CentreY
	Size# = Sqr(X * X + Y * Y)
	Rot# = ATan2(Y, X)
	Polygon = PolyImage2(Sides, Size, Rot, 255, 255, 255)

	SetBuffer BackBuffer()
	Cls
	TileImage Polygon, CentreX, CentreY
	FreeImage Polygon
	Text CentreX, CentreY, "Sides = " + Sides + "  Rot = " + Rot, 1, 1
	Flip True

	If MouseHit(1)
		Sides = Sides + 1
		If Sides > 12 Then Sides = 3
	EndIf

Wend

End

;Creates an image of a polygon and returns it to specified handle
;****************************************************************
Function PolyImage2(numSides, size, rotation, r, g, b)

	Color r, g, b
	
	polygon = CreateImage(size * 2 + 1, size * 2 + 1)
	SetBuffer ImageBuffer(polygon)
	Origin size,size

	Local OldX#, OldY#
	Local NewX#, NewY#
	Local AngleStep# = 360 / numSides
	Local Angle#
	
	For i = 0 To numSides
		Angle = i * AngleStep + rotation
		OldX = NewX
		OldY = NewY
		NewX = size * Cos(Angle)
		NewY = size * Sin(Angle)
		If (i <> 0)
			Line OldX, OldY, NewX, NewY
		EndIf
	Next
	
	Return polygon
End Function

The function is not only a lot shorter but more flexible as numSides can be anything with no need to add code.

I also added a bit more functionality in the mainline like rotating the polygon according to the mouse position and tiling the image for a cool but cheap effect. Hence the switch to continuous drawing and flip etc.