Variables on a Node
Part of the Nodes and Scenes section of Coddy's Godot journey. Lesson 13 of 28.
A variable made at the top of a script, outside any function, belongs to the node. It keeps its value from frame to frame, and every function of the script can use it:
extends Node2D
var speed = 150
func _process(delta):
position.x += speed * deltaBecause it lasts, a node variable can change over time. Add to speed on every frame and the node goes faster and faster:
func _process(delta):
speed += 50 * deltaA var made inside a function is made again on every call and forgotten at the end.
Challenge
EasyMake the robot start still and speed up.
- In
_process(), add a new linespeed += 200 * delta. It adds tospeedon every frame, not to the position. Keepvar speed = 0at the top as it is. - Move the robot by
speed: replaceposition.x += 100 * deltawithposition.x += speed * delta.
Press Play: the robot creeps off, then goes faster and faster. Then Check.
Try it yourself
extends Node2D
var speed = 0
func _process(delta):
position.x += 100 * delta
All lessons in Nodes and Scenes
1Your First Godot Game
What Is Godot?Ready Runs OncePrint in GodotThe Scene TreeSet a PositionMove a Node Once3Values You Can Tune
Variables on a NodeConstantsExport VariablesVector2 MathWrap Around the ScreenYour Own FunctionsPractice on your own: Godot playground