Your Own Functions
Part of the Nodes and Scenes section of Coddy's Godot journey. Lesson 18 of 28.
Godot calls _ready() and _process() by itself. You can also write your own functions, to give a few lines a name:
func jump_to_start():
position = Vector2(50, 250)A function runs only when code calls it, by writing its name with brackets: jump_to_start(). Call it from _process() and it runs on every frame. Call it from _ready() and it runs once.
A good name says what the function does. Then _process() reads like a list of steps: move, then wrap.
Challenge
EasyWrap the robot at the right and bottom edges with your own function.
- Under
_process(), writefunc wrap_around():holding theifforxpast640, plus one that setsypast360back to0. - In
_process(), callwrap_around()after the robot moves, in place of theif.
Press Play: the robot drifts down and right, and always comes back on the screen. Then Check.
Try it yourself
extends Node2D
var velocity = Vector2(200, 100)
func _process(delta):
position += velocity * delta
if position.x > 640:
position.x = 0
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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