Running a function with vector change inside _process issue

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By eduard.parvu

Hi,

Newcomer to Godot here as the question will shortly imply. I'm following the documentation and just started the "my first game" section and ran into an issue. I moved the whole input logic inside a separate function _setup_input(velocity) which changes the x and y positions based on key presses and called it inside _process function just so it would look a little cleaner than the example and the character is not moving. Once I move the logic back to the _process function it works and I can't understand why.
func _ready():
screen_size = get_viewport_rect().size

func _process(delta):
var velocity = Vector2() # the player's movement velocity

setup_input(velocity)

if velocity.length() > 0:
	velocity.normalized() * SPEED
	$AnimatedSprite.play() # $ returns the node at the relative path from this node, shorthand for get_node()
else:
	$AnimatedSprite.stop()
	
position += velocity * delta

position.x = clamp(position.x, 0, screen_size.x)
position.y = clamp(position.y, 0, screen_size.y)

func setup_input(velocity):
if Input.is_action_pressed("ui_right"):
	velocity.x += 1
if Input.is_action_pressed("ui_left"):
	velocity.x -= 1
if Input.is_action_pressed("ui_up"):
	velocity.y += 1
if Input.is_action_pressed("ui_down"):
	velocity.y -= 1
:bust_in_silhouette: Reply From: kidscancode

velocity is a class variable. You don’t need to pass it between functions in the same script.

velocity is a function variable in the example. Yes I can make it a class variable and it will work. I was just surprised that when passing the velocity instance to the function it uses pass by copy and the copy is on another memory segment which is why it didn’t work. I recently found out that Vector2 is atomic so it will be passed this way while other things like nodes, scenes, arrays, dictionaries are passed by reference which is what I was expecting

eduard.parvu | 2018-04-15 16:25