0 votes


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


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

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
in Engine by (12 points)

1 Answer

0 votes

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

by (21,981 points)

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

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.