How to create a circle with line2d?

Godot Version

Godot 4.2 Stable

Question

I want to creat a Circle2D
this is my codes:

@tool
extends Polygon2D

class_name Circle2D

@export var cuts = 128:
	get:
		return cuts
	set(value):
		cuts = value
		
		update_points()

func update_points():
	var pos_list: PackedVector2Array = PackedVector2Array()
	var correct_cuts = cuts + 3
	
	for cut in range(correct_cuts):
		var radian = (2 * PI / 360) * (360 / correct_cuts) * (cut + 3)
		var radian_pos = Vector2(cos(radian), sin(radian))
		pos_list.append(radian_pos)
	
	polygon = pos_list

but the circle has a bug:

Do you really need this complicated formula?

If you just want a circle shape, this should work:

func update_points():
	var pos_list: PackedVector2Array = PackedVector2Array()
	var step = (2 * PI) / cuts
	for cut in range(cuts):
		var radian = step * cut
		var radian_pos = Vector2(cos(radian), sin(radian))
		pos_list.append(radian_pos)
	
	polygon = pos_list
1 Like

Ignoring the fact that the position calculation formula itself is overly complicated:

The issue is that in this formula

var radian = (2 * PI / 360) * (360 / correct_cuts) * (cut + 3)

the calculation “360 / correct_cuts” is an integer division, which with a “correct_cuts” value of 131 results in the value 2, instead of the wanted value of ~2.75.
This results into the circle only being drawn for 232 degrees, which is what can be seen in your screenshot

You can fix this either by converting the “correct_cuts” variable into a float like this:

var radian = (2 * PI / 360) * (360 / float(correct_cuts)) * (cut + 3)

Or by using the code from the comment above.

Why the code from the previous comment fixes the issue

The code from the comment above fixes the issue in this line

var step = (2 * PI) / cuts

because “(2 * PI)” is a float and turns the division into a float division instead of the integer division in your current code

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.