Reputation: 137
Via script, I am creating a static body that has a child panel container that has a child label node. When text is applied to the label, the top-left corner of the panel container is centered on the static body, resulting in off-center text (see screenshot below).
The following code is used to create the nodes:
func create_distance_marker():
var static_body = StaticBody2D.new()
static_body.name = "distance_location"
static_body.position = Global.mid_point
add_child(static_body)
var panel_container = PanelContainer.new()
panel_container.name = "panel_container"
static_body.add_child(panel_container)
var distance_label = Label.new()
distance_label.name = "distance_label"
distance_label.text = str(Global.distance)
panel_container.add_child(distance_label)
The following code is used to place the static body and update the label text:
func display_distance_marker():
var static_body = get_node("distance_location")
static_body.position = Global.mid_point
Global.distance = round(point_one.distance_to(point_two) / 35)
var distance_label = get_node("distance_location/panel_container/distance_label")
distance_label.text = str(Global.distance)
I've found similar questions already asked, but the answers were geared towards configuring the nodes via the inspector. I suspect that the align and valign controls to need to be set to 'center', but can't figure out how to do that via script.
Upvotes: 0
Views: 685
Reputation: 137
So, the first step was to simplify things and eliminate the panel container
. Then I used conditional logic to center both single-digit and double-digit distances within the distance marker circle.
func display_distance_marker():
var distance_label
var static_body = get_node("distance_location")
if Global.click_and_drag and Global.shift_pressed:
static_body.position = Global.mid_point
static_body.visible = true
Global.distance = round(point_one.distance_to(point_two) / 35)
distance_label = get_node("distance_location/distance_label")
distance_label.text = str(Global.distance)
var label_size = distance_label.size
var label_coord
if Global.distance < 10:
label_coord = Vector2(-.1 * label_size.x, -10)
else:
label_coord = Vector2(-.2 * label_size.x, -10)
distance_label.position = label_coord
else:
static_body.visible = false
Upvotes: 0