DDoop
DDoop

Reputation: 33

Godot: add_child() on an instanced node's children to recursively create objects

I'm creating a little program that creates image patterns like these using line segments that rotate around each other: image from Engare Steam store page for reference

How do I tell Godot to create instances of the Polygon2D scene I'm using as line segments with origins on Position2D nodes that exist as children in the Polygon2D scene? Here is a sample of my code:

const SHAPE_MASTER = preload("res://SpinningBar.tscn")
...
func bar_Maker(bar_num, parent_node):
    for i in range(bar_num):
        var GrabbedInstance = SHAPE_MASTER.instance()
        parent_node.add_child(GrabbedInstance)
        bar_Maker(bar_num - 1, $Polygon2D/RotPoint)
...
func _physics_process(delta):
...
    if Input.is_action_just_pressed("Switch Item"): # from an older version of the program, just bound to ctrl
        bar_Maker(segment_count, BarParent)

bar_num is the number of bars to instance, set elsewhere (range 1-6).
parent_node in the main scene is just a Node2D called BarParent.
The SpinningBar.tscn I'm instancing as GrabbedInstance has a Position2D node called "RotPoint" at the opposite end of the segment from the object's origin. This is the point I would like successive segments to rotate around (and also put particle emitters here to trace lines, but that is a trivial issue once this first one is answered).

Running as-is and creating more than 1 line segment returns "Attempt to call function 'add_child' in base 'null instance' on a null instance." Clearly I am adding the second (and later) segments incorrectly, so I know it's related to how I'm performing recursion/selecting new parents for segments 1+ node deep.

Upvotes: 0

Views: 9549

Answers (1)

DDoop
DDoop

Reputation: 33

Bang your head against the wall and you will find the answer:

func bar_Maker(bar_num, parent_node):
    for i in range(bar_num):
        var GrabbedInstance = SHAPE_MASTER.instance()
        parent_node.add_child(GrabbedInstance)
        var new_children = GrabbedInstance.get_children()
        bar_Maker(bar_num - 1, new_children[0])

If someone is aware of a more elegant way to do this please inform me and future readers. o7

Upvotes: 2

Related Questions