In programming, composition means assembling complex things from smaller, simpler ones.
Imagine building a castle out of Lego bricks. Each brick is simple, but you can create houses, bridges, and more by putting them together in different ways.
Similarly, in games, we can use composition to create interesting characters and levels by combining smaller parts, including equipment, abilities, and hazards.
Under the hood, the parts we combine in the code can be objects, classes, or even functions.
Composition in Godot
Godot is built on composition and promotes it. Scenes, scripts, and nodes are all building blocks you can combine in infinite ways to create your games. Every time you make and instantiate a scene in another scene, you're doing composition!
The same is true of nodes.
For example, to create a player character, you might use a combination of a CharacterBody2DCharacterBody2D, Sprite2DSprite2D, CollisionShape2DCollisionShape2D, and AnimationPlayerAnimationPlayer node.
Each of these nodes works mostly independently and focuses on a specific feature:
The CharacterBody2DCharacterBody2D handles movement and detects collisions.
The Sprite2DSprite2D displays the character's texture.
The CollisionShape2DCollisionShape2D defines the character's collision box.
And the AnimationPlayerAnimationPlayer plays animations.
The interesting aspect is that you can reuse these nodes in many scenarios. For example, a chest, a bird, or a monster could use a Sprite2DSprite2D and CollisionShape2DCollisionShape2D node to display different images and behaviors.
In other words, a system built around composition like Godot's is very flexible and scalable.
Become an Indie Gamedev with GDQuest!in GDSchool
Don't stop here. Step-by-step tutorials are fun but they only take you so far.
Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.