How to shape Polygon2D into a circle.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Melodi

Hey I want to create a circle shaped polygon2D and I will be putting textures on it. However I can not find any information on how to do so. I want a circle object like wheel that will roll and will change it’s texture for wheel and other stuff. How can I achieve this thank you all. Also 1 method I tried is shaping a circle sprite in to polygon2d but it reduces great performance and it does not result in an actual circle instead a 1500~edged polygon.

:bust_in_silhouette: Reply From: PepijnWe

If you use CollisionShape2D, you can selected a CircleShape2d

Yes I know that, but I am trying to achieve a circle texture base that I will be putting on textures. Is there a way to put textures on CollisionShape2D ?

Melodi | 2020-09-08 22:35

:bust_in_silhouette: Reply From: how does godot work

so the numSides is the number of sides/faces and the perimeter length is the length of the perimeter.

func generatePolygonV2(numSides, perimeterLength):
var lineLength : float = perimeterLength/numSides
var lineAngle : float = -360.0000000000/numSides
var currentAngle : float = 0.0000000000

var newPolygon = Polygon2D.new()
var polygonVectors : PoolVector2Array

for i in numSides:
	var newVector
	
	if i == 0:
		currentAngle += lineAngle
		newVector = Vector2(lineLength * cos(deg2rad(currentAngle)),lineLength * sin(deg2rad(currentAngle)))
		polygonVectors.append(newVector)			
	else:
		currentAngle += lineAngle
		newVector = Vector2(polygonVectors[i-1].x + lineLength * cos(deg2rad(currentAngle)),polygonVectors[i-1].y + lineLength * sin(deg2rad(currentAngle)))
		polygonVectors.append(newVector)

newPolygon.polygon = polygonVectors
newPolygon.color = Color(1,0,1)
node2d.add_child(newPolygon)
polygon = newPolygon

something like this? The only problem with my method is the polygon generated is not centered. I have an idea on how i could fix that but yeah i’m lazy.

:bust_in_silhouette: Reply From: SanderVanhove

Here is some code that would generate a circle polygon:

func generate_circle_polygon(radius: float, num_sides: int, position: Vector2) -> PoolVector2Array:
	var angle_delta: float = (PI * 2) / num_sides
	var vector: Vector2 = Vector2(radius, 0)
	var polygon: PoolVector2Array

	for _i in num_sides:
		polygon.append(vector + position)
		vector = vector.rotated(angle_delta)

	return polygon

This would generate a polygon circle of a certain radius with a certain num_sides with position as the center point.