How to draw Rect2 in the center position of viewport

crimson3crimson3 Posts: 3Member
edited January 28 in Programming
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 ?

Tagged:

Tags :

Answers

  • MegalomaniakMegalomaniak Posts: 1,087Admin
    Answer ✓

    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.

  • crimson3crimson3 Posts: 3Member
    edited January 28 Answer ✓

    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)
    
  • crimson3crimson3 Posts: 3Member

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

Sign In or Register to comment.