Vector2 Math
Part of the Nodes and Scenes section of Coddy's Godot journey. Lesson 16 of 27.
You can do math with a Vector2. Adding two vectors adds the xs and adds the ys:
Vector2(100, 50) + Vector2(10, 5) # (110, 55)Multiplying by a number multiplies both: Vector2(100, 50) * 2 is (200, 100). That is how velocity * delta works.
A vector's length is how far it reaches in a straight line. .length() works it out:
var step = Vector2(3, 4)
print(step.length()) # 5.0For a velocity, the length is the real speed. A robot moving 120 right and 90 up each second covers 150 pixels a second.
Challenge
EasyThe script has a variable velocity, Vector2(120, -90).
- When the game starts, print the robot's real speed, its length:
Speed: 150.0. - On every frame, move the robot by
velocity, per second.
Try it yourself
extends Node2D
var velocity = Vector2(120, -90)
func _ready():
pass
func _process(delta):
pass
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