See all glossary terms

Composition

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 CharacterBody2D, Sprite2D, CollisionShape2D, and AnimationPlayer node.
Each of these nodes works mostly independently and focuses on a specific feature:
  • The CharacterBody2D handles movement and detects collisions.
  • The Sprite2D displays the character's texture.
  • The CollisionShape2D defines the character's collision box.
  • And the AnimationPlayer 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 Sprite2D and CollisionShape2D node to display different images and behaviors.
In other words, a system built around composition like Godot's is very flexible and scalable.

See Also

Related terms in the Glossary