How to insert a Vector2 into an array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ArAdev
:warning: Old Version Published before Godot 3 was released.

Hi, I need to insert Vector2 into arrays so I can use it as separate coordinates. I tried using Vector2Array but I don`t get how to do it in the documentation.Tried this:

var vector_array = Vector2Array(my_array)

But the results were that it acts like a string, the values are fine, even the structure is like the Vector2( x, y ) , but when I can from the array the x or the y coordinate, it always say:

Invalid get index ‘x’ (on base: ‘Array’).

Also the value that I`m adding to the array is a Vector2, but apparently in the array always works as a string.

HI there ArAdev,

Sorry to ressurect an old question, but could you elaborate on the way this worked for you? I am also trying to figure out how to add a vector to an array. In my case, I want to instance objects at different co-ordinates on the screen and I was wanting to do so by passing the points through into an array and then instancing them through there.

In the answer below,
It seems that you first initialize that my_array is a 2D vector, this would be so that each entry into the array has a x and y co-ordinate. Then the array is created from that variable. Going forward, what did you do to get it right? If you could let me know, that would be great!

# var my_array = Vector2(x,y)
var vector_array = [my_array]

CodeJBDA | 2018-11-08 05:19

You probably, (most likely) don’t need this anymore but ill still answer, you can just do:

var array = []
array.append(Vector2(x, y))

That worked for me at last.

sian2005 | 2020-08-08 18:34

:bust_in_silhouette: Reply From: rolfpancake

If you want to initialize an array at its declaration you have to pass an array.

# var my_array = Vector2(x,y)
var vector_array = [my_array]

You can also declare your vector_array as an empty array and then fill it with append. Used this for a list of positions of a node:

var position_list = Array()

func _physics_process(delta):
  position_list.append(position)

Thanks a lot, this worked as I wanted!

ArAdev | 2017-12-20 23:19