exs. Node2D

func _ready():
	rect()
		
func rect():
	var x = get_viewport().get_visible_rect().size.x/2
	var y = get_viewport().get_visible_rect().size.y/2
	var w = 20
	var h = 20
	#var position.middle = ??
	rect = Rect2(x,y,20,20)

A draw_rect call will now draw a square of 20px in the middle of the viewport but the origin point is 0,0 of Node2D,in a default viewport of godot it draws the rectangle at 512y,300x but i want it to be 512-10y,300-10x but i dont want to put those values in there rather i would want to use w and h variables so what math and function should i do to make then x and y position - half of w and h ?

Untested pseudo code quickly modified from yours as example of how I would go about it:

exs. Node2D
func _ready():
    rect(20, 20)

func rect(width, height):
    var x = get_viewport().get_visible_rect().size.x/2
    var y = get_viewport().get_visible_rect().size.y/2
    var w = width/2
    var h = height/2
    rect = Rect2(x - w, y - h, w, h)

Hope this helps steer you in the right direction.

if anyone wants the make the draw_rect position at the center of viewport rathar than originating from the center define the w and h variables/consts before getting the x and y pos if you are defining their values within a func and at the end of x or y value add "-w/2" and "h/w" respectively

func rect():
	var w = 1024
	var h = 600
	var x = get_viewport().get_visible_rect().size.x/2-w/2
	var y = get_viewport().get_visible_rect().size.y/2-h/2
	rect = Rect2(x,y,w,h)

@Megalomaniak thank you for the help btw. Did a quick math after few hours of gaming got what i wanted XD

4 years later