I am slowly working on my first prototype, and I encountered an issue with arrays.
I have an array called “segments” that have instances of snake body inside it, so I can control each part individually through one .gd file. I however encountered a problem that I don’t know how to reference self - as in matter of referencing the current instance of segment.
I simply tried this:
my_segment = segments[self]
It did not work and I got error message
Invalid get index player_tile:<StaticBody2D#77057756780> (on base: Array)
Did someone needed to do something similar? I would appreciate any help.
Thanks
Arrays are indexed by a an integer. Indexing by self doesn’t make sense.
What exactly do you mean by the current instance of segment? If you mean the snake’s head, that will probably be at the beginning of the array, so segments[0]. Or you can loop over the segments with a for loop:
for current_segment in segments:
# do something with the segment
I have snake head as a separate node in my project as I use it as Player node.
And by current instance of segment I mean that, as I said in original post, I want to use one .gd script to control every segment of the snake’s body. I made the script so each segment of the snake → each “square” of the body if you imagine the original game is instanciated as a child of the Player node.
func Grow():
# Instantiate the new body segment
var instance = body.instantiate()
add_child(instance)
# Some starting positioning code
# Add the new segment to the list
global.segments.append(instance)
This means that every single one if these child nodes are also in the array and now, for the problematic part. I need to somehow get the instance of the body segment that the code should edit. For start I am putting 5 instances of the body to the array
func _ready():
var length := 5 # this is elsewhere in the code but that's not important
for l in length:
Grow()
And I don’t want to apply every function (rotate left, rotate right,…)to every single segment in the array because that would not make sense → I don’t want to move every segment up if head (player) is moving up, I want to move up only the segment that is directly following the head, every other segment should follow the segment before that.