Mr Laliberte

Math Operators in GDScript

Game Development with Godot · Variables and Data · Lesson 2

Courses › Game Development with Godot › Math Operators in GDScript

What Is an Operator?

An operator is a symbol that tells the computer to do something with two values, usually numbers. You already know these symbols from math class. Today we’ll use them inside GDScript.

The Four Basic Operators

Symbol Name What It Does Example
+ Addition Adds two numbers together 5 + 3 = 8
- Subtraction Subtracts one number from another 10 - 4 = 6
* Multiplication Multiplies two numbers together 6 * 2 = 12
/ Division Divides one number by another 20 / 5 = 4

Using Operators With Variables

Variables store numbers. Operators let us change what’s stored inside them. Here’s the pattern:

var health = 100
health = health - 15
print(health)   # prints 85

Read the second line as: “take whatever is currently in health, subtract 15, and store the result back into health.” The = sign means “store this value”, it does NOT mean “equals” the way it does in math class.

Shortcut Operators

Because “take a variable, do math, and store it back into itself” is so common, GDScript gives us a shortcut:

Shortcut What It Does Same As
+= Adds and stores health = health + 10
-= Subtracts and stores health = health - 10
*= Multiplies and stores score = score * 2
/= Divides and stores score = score / 2

Example using the shortcut:

var health = 100
health -= 15
print(health)   # prints 85, same result as before, shorter to write

Order Matters

The computer follows the same order-of-operations rules you learned in math class: multiplication and division happen before addition and subtraction, unless you use parentheses.

var total = 2 + 3 * 4
print(total)   # prints 14, NOT 20

var total2 = (2 + 3) * 4
print(total2)  # prints 20, parentheses go first

Bonus: The Modulo Operator (%)

% gives you the remainder after division. We won’t need it much yet, but it’s useful later for things like “every 3rd enemy drops a coin.”

print(10 % 3)   # prints 1  (10 divided by 3 is 3 remainder 1)

Quick Reference Card

SymbolMeaning
+add
-subtract
*multiply
/divide
+=add and store
-=subtract and store
*=multiply and store
/=divide and store
%remainder (bonus)

Welcome back