Godot Version
4.3
Question
`So im trying to center a list of sprites in the x axis in respect to the viewport’s width. In the demonstration I attached, Wi is the sprite width, and S is the spacing (the spacing is constant in each sprite iteration). These are generated via code, and can vary in quantity based on what item i hover at.
The process has a starting position, which tells me the point where this list starts. Now, my way of doing this was to modify the starting position value to a point where all the popups become centered.
The formula i made for this was: the starting position = (the viewport’s width + the container’s width)/2
The container’s width is just all the sum of the sprite widths and spacing. if this formula correctly makes a list of sprites centered, then my generation process must have a problem with it. Please take a look at my code;
func position_popups(popups: Array, scaler: Vector2, spacing: float):
var container_width:float = 0
var all_line_widths:Array
var first_dim_area:float = get_viewport_rect().size.x
var starting_pos:floatfor popup in popups:
var popup_width:float = popup.get_rect().size.x * scaler.xcontainer_width += popup_width
container_width += spacing * (popups.size()-1)
starting_pos = (first_dim_area/2) - (container_width/2)var current_x: float = starting_pos
var current_y: float = offset_yfor popup in popups:
popup.offset_to_bottom() #ignore this
var popup_width: float = popup.get_rect().size.x * scaler.x
var popup_height: float = popup.get_rect().size.y * scaler.ypopup.position = Vector2(
current_x + (popup_width / 2),
current_y
)
current_x += popup_width + spacing
r/godot - Cant center a list of popups in GDscript, what did I do wrong?
The result wasn’t much promising. The list of popups went to the side of the screen.
Some notes:
could the parent of the popups have an x position that disrupts this process? Nope, all parent nodes are positioned 0 at the x axis
What does the popup node consist of? A sprite2d node? It consists of a node2d, and a sprite2d as its child. It also has a collisiionshape2d for debugging. All functions work properly, the get_rect() function is actually just a custom function that returns the sprite2d’s rect, not the node2d itself. The offset_to_bottom() function is for making the popups on equal levels in depth, that’s why they are straightened like that in the screenshot.
If you have any questions, ill be glad to answer.`