Thursday, March 21, 2019

11. Random

Under a Node, we attach a script and using code create a Label and Timer.


The 'timeout' signal is emitted every 2 second and new random numbers are printed by this script.



extends Node

export (int) var max_int = 10
var label = Label.new()
var timer = Timer.new()
var rand_val

func _ready():
    randomize()
    add_child(label)
    add_child(timer)
    rand_val = randi() % max_int
    timer.connect("timeout",self,"_on_Timer_timeout")
    var rand_float = "%.2f" % randf()
    label.set_text("Random Integer: " + str(rand_val) +
        "\nRandom Float: " + rand_float )
    label.set_align(Label.ALIGN_CENTER)
    label.set_valign(Label.VALIGN_CENTER)
    label.margin_bottom = 200
    label.margin_right = 200
    timer.wait_time = 2
    timer.start()
 
 
func _on_Timer_timeout():
    rand_val = randi() % max_int
    var rand_float = "%.2f" % randf()
    label.set_text("Random Integer: " + str(rand_val) +
        "\nRandom Float: " + rand_float)


The output, with window size of 200,200, after a few seconds:


No comments:

Post a Comment