Constants
Part of the Nodes and Scenes section of Coddy's Godot journey. Lesson 14 of 28.
Some values never change while the game runs, like a robot's top speed. Use a constant for them. It is made with const instead of var:
const SPEED = 250Constants are written in CAPITALS, so readers see the value is fixed. To change it, edit the number where it is made.
A line that changes a constant is an error. Godot catches it before the game starts. The Console says Cannot assign a new value to a constant and names the line.
Challenge
EasyMake the game start, with a faster robot.
- Delete
_ready()and the line inside it: a script cannot change a constant. - Give
SPEEDthe value300where it is made, and keep it aconst.
Press Play: the game starts and the robot moves left at 300 pixels a second. Then Check.
Try it yourself
extends Node2D
const SPEED = 200
func _ready():
SPEED = 300
func _process(delta):
position.x -= SPEED * 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