+1 vote

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?

in Engine by (34 points)

2 Answers

–3 votes

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
by (15 points)

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.

+5 votes

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):
    object.update_vec(3,3)

func _ready():
    var thing = MyClass.new()

    print(thing.vec)
    my_func(thing)
    print(thing.vec)
by (5,278 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.