Need help understanding the reason for "velocity = Vector2()" at beginning of _process function....

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

In the http://docs.godotengine.org/en/3.0/getting_started/step_by_step/your_first_game.html tutorial, the _process function begins with the line:

velocity = Vector2()

but the beginning of the script already declares the variable and ?sets its type? outside of the function with the line:

var velocity = Vector2()

I am having trouble understanding what this line in the function is accomplishing. I know it is necessary, because the behaviour of the object is drastically changed when I comment it out. I am sure there is something profound that I am missing here that will cause me further problems as I move forward. I have a suspicion that this is something to do with the “dynamic typed language” of GDScript, but ANY guidance is definitely appreciated.

Thanks

extends Area2D

export (int) var SPEED # how fast the player will move (px/sec)
var velocity = Vector2() # the player's movement vector
var screensize # size of the game window

func _ready():
	# Called every time the node is added to the scene.
	# Initialization here
	screensize = get_viewport_rect().size
  
    func _process(delta):
    	# Called every frame. Delta is time since last frame.
    	# Update game logic here.
    	velocity = Vector2()
    	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_down"):
    		velocity.y += 1
    	if Input.is_action_pressed("ui_up"):
    		velocity.y -= 1
    		
    	if velocity.length() > 0:
    		velocity = velocity.normalized() * SPEED
    		$AnimatedSprite.play()
    	else:
    		$AnimatedSprite.stop()
    	
    	position += velocity * delta
    	position.x = clamp(position.x, 0, screensize.x)
    	position.y = clamp(position.y, 0, screensize.y)
:bust_in_silhouette: Reply From: kidscancode

Without arguments, the vector constructor defaults to zero.

velocity = Vector2()

is equivalent to

velocity = Vector2(0, 0)

This line is setting the character’s velocity to 0 before checking the inputs. This makes staying still the default condition, so that the character will only move when a key is held down.

Thanks for your answer. It really helped. I knew it should seem obvious once I got it. I think that using:

velocity = Vector2D(0,0)

would have been more readily accessible… It also now makes sense as a whole. I couldn’t figure out how the velocity of the player was being clamped and not continuously accelerating while the key was pressed (which consequently happens when that line is commented out…)

Thank You!

Wraith1978 | 2018-03-28 11:45