Vector2 Math
Part of the Nodes and Scenes section of Coddy's Godot journey. Lesson 16 of 28.
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
EasyPrint the robot's real speed, then fly it.
- In
_ready(), print"Speed: "and the length ofvelocity, with.length(). - In
_process(), move the robot byvelocityper second, withdelta.
Press Play: the Console shows Speed: 150.0 and the robot flies up and right. Then Check.
Try it yourself
extends Node2D
var velocity = Vector2(120, -90)
func _ready():
pass
func _process(delta):
pass
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