Instance a scene in every so often in Line2D line.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Chevi

I’m making a Pacman and have my Pellet.tscn, and I don’t want to individually place hundreds of them so I had the idea to have a Line2D and instance the pellets through it. how would I do it?

My Line2D stretches from 0,0 to 100,0 to 100,100 and I want to instance a pellet every 10 pixels of the line.

Help is greatly appreciated.

:bust_in_silhouette: Reply From: Moldor2

First, add points along your Line2D where you want to spawn pellets. Then declare a variable holding your pellet scene:

var pellet = load("res://pellet.tscn")

Once you do that you would then make use of a for loop as well as a some built-in functions that the Line2D has. For example:

func instanceLine():
 var pointCount = $Line2D.get_point_count()
 for i in range(pointCount): #will iterate for each point on the Line2D
    var child = pellet.instance() #create a new "object" of the pellet
    #set the position to the position of the point
    child.position = $Line2D.get_point_position(i)
    #initialize the child into the scene tree under a placeholder node

This is how I would do it, then I would have the pellet scene have a script on it that would have a reference to it’s parent using get_parent() and then have a function that waits until “pacman” runs into and eats the pellets