How do I pass Vectors by reference/pointer?

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

I want to update my velocity vector in a function, but am unsure how to pass the function the reference to the vector instead of a copy.

Any ideas?

:bust_in_silhouette: Reply From: Flying_Dindoleon

Is the function inside the same script as the vector ?
If so, I think you don’t have to pass it as an argument to update it.

var vector = Vector2( 1, 1 )

func _update_vector()
    vector.x += 0.5
    vector.y += 1

Otherwise, if it’s inside another script, use return to update it :

Script 1 ( main ) :

var vector = Vector2( 1, 1 )
var function_script = preload("res://tscn/functions_script.tscn").instance()
add_child( function_script )

vector = function_script._update_script( vector )

Script 2 ( inside “functions_script.tscn” ):

func _update_script( vector ):
    var new_vector = vector
    new_vector.x += 0.5
    new_vector.y += 1
    return new_vector

I wanted to avoid using the global velocity vector and instead pass it as an argument, otherwise I find it difficult to keep track of what is changing it.

mofro | 2017-07-18 11:21

:bust_in_silhouette: Reply From: avencherus

There is no syntax to make something a pointer, just a few bits that pass by reference.

You can pass an object/class into a function, and it passes by reference. From there you can target it’s properties and update them. Whether or not this is ideal practice, you’ll have to judge for yourself.

If you want to completely avoid constructing a new vector as well, you can update it’s x and y values.

Here is example of these two things.

extends Node2D

class MyClass:
	var vec = Vector2(1,1) setget update_vec
	func update_vec(x, y):
		vec.x = x
		vec.y = y

func my_func(object):

func _ready():
	var thing =