@george2868 said:
Hi TwistedTwigle,
Thank you for taking the time to look at the code snippet of a newbie! :)
The position property is the position of the node relative to its parent scene, and since you are parenting each node to the next segment in the chain, you don't need to multiply by i since the position is only relative to its parent
Yes you are right, but if I change to copy.set_position(Vector2(0, 32))
and set the length
variable to 3
or greater then the segments are not placed beneath each other (please see the attached project)
Yup, you're right! I totally missed that when testing. After debugging and some head scratching, I found out the issue though and thankfully its simple to fix. The issue is that you are using KinematicBody2D nodes and they ignore having their position changed for a single frame as they setup their physics, so you have to yield for a single frame and then set the position, and then it will work as expected. Here's the code I used:
extends Node2D
export var length = 2
onready var segment_current = get_node("segment0")
func _ready():
length = abs(length) - 1
for i in range(length):
segment_current = create_segment(segment_current, i+1)
yield(get_tree(), "idle_frame")
segment_current.position = Vector2(0, 32);
segment_current = get_node("segment0")
segment_current = segment_current.get_node("segment1")
func _physics_process(delta):
segment_current.rotation += -1 * delta
pass
func create_segment(seg, i):
var copy = seg.duplicate()
copy.name = "segment" + str(i)
segment_current.add_child(copy)
#copy.set_position(Vector2(0, i*32))
copy.set_position(Vector2(0, 32))
return copy
Then it should work as expected!
Side note: the only reason I figured out it was a KinematicBody2D node quirk that causes the issue is because if you use a Node2D node, the yield is not necessary and it works without any issue. It did take me a bit to figure out that was the issue though, as I thought it was something with the code for setting the position initially until I did a long chain of print statements for debugging.