Tuesday, March 19, 2019

3. Using MarginContainer, VBoxContainer, Label and TextureRect nodes

We use several nodes, created by code, to create a simple GUI. Our window size is 200 by 200, set in the Project Settings. First we set the background color as lime.


Using a Node with attached script, we first create a MarginContainer, then set its anchors and margins so there is 50px margin on all four sides.


We then have a VBoxContainer as its child. We set the separation as 25, so to have some spacing between the 2 child nodes.


The child nodes are Label (text of Godot 3.1 with color red), and TextureRect, with the image of the Godot icon.


This is the script


extends Node

var mc = MarginContainer.new()

func _ready():
    VisualServer.set_default_clear_color(ColorN("lime"))
    mc.anchor_right = 1
    mc.anchor_bottom = 1
    mc.margin_left = 50
    mc.margin_top = 50
    mc.margin_right = -50
    mc.margin_bottom = -50
    var vbox = VBoxContainer.new()
    vbox.add_constant_override("separation",25)
    mc.add_child(vbox)
    var lbl = Label.new()
    lbl.text = "Godot 3.1"
    lbl.add_color_override("font_color", Color(1,0,0,1))
    vbox.add_child(lbl)
    var tr = TextureRect.new()
    tr.texture = load("res://icon.png")
    vbox.add_child(tr)
    add_child(mc)

This is the output:


No comments:

Post a Comment