• 2D
  • 2D custom circle not centered

Hey there, I've started using Godot recently and thought I'd just create a little game to get to know it better. I've decided to make some kind of rotationary pong (the rackets rotate around the center of the screen). To represent the circle where the rackets can move, I've created a new Node2D node where I've overloaded the _draw function so it draws a circle. The circle is perfect except for one thing: it is not centered as it should be when following this code.

extends Node2D

export var radius = 100
export var segments = 64

func _ready():
	position = Vector2(get_viewport().size.x/2, get_viewport().size.y/2)

func _process(delta):
	pass

func _draw():
	drawCircle()

func drawCircle():
	var circlePoints = Array()
	var stepAngle = deg2rad(360 / segments)
	for i in range(segments + 1):
		circlePoints.append(Vector2(position.x + (cos(i * stepAngle) * radius), position.y + (sin(i * stepAngle) * radius)))
	for i in range (segments):
		draw_line(circlePoints[i], circlePoints[i + 1], Color(128, 128, 128), 4, true)

I've done some tests and the position of my node in the viewport is as it should be but the circle is not as you can see there

The center is where the racket is so technically I should have a circle around it (here my circle has only 8 segments but I can adjust that) but it seems like it doesn't want to. In debug mode I've looked at the values of the points that compose the circle and all the values are accurate (all around the middle) but once it's drawn it is suddenly on the bottom right corner.

Any idea ?

Without testing the code, I think the problem is because you are adding the Node2D's position.

_draw and the drawing related functions use coordinates relative to the position of the node whose _draw function is being used.

For example, if you are using _draw with a node at position (10, 10), then calling draw_circle(Vector2(0,0), Color(1,1,1,1), 16) will draw a 16px circle at (10, 10).

One way you can test if the Node2D's position is the problem is by moving it to origin, (0, 0), and see if it is drawing correctly.

Oh ok then it's a basis problem: the drawing is done using the Node2D's local coordinate but I was using it like it was done with global coordinate. Thanks. I just deleted the position.x and the position.y in the coordinates for the points of the circle and now it's working.