Posted June 04, 2023 by dustdfg
#godot #composition #software-design #patterns
Godot is a great open-source game engine that allow to create beautiful and fun games. I use it for my games and I think I got a drop of blessing when worked on this demo for a jam. I understood how to use composition in Godot and how it can help you to create better games with this engine. I hope you will like puzzles I created for this and maybe other my games. Please comment this devlog and let me know what do you think about it. Maybe you can told me other ways to use composition in Godot? I will really appreciateit:D
First of all I want to tell you how I saw composition before creating this game. I thought that composition is a pattern when one object contains another object and uses it for its own needs. I thought that composition is a type of relations when parent always know about it's child and interacts with it (calls child's functions, read something from child and etc.) It is really so but I saw only one side of this pattern. I couldn't imagine that parent may not know about child, may not interact with it.
This game is based on the two simple mechanics:
Honestly, it is all the mechanics and they are all implemented via composition :D
Let's take a look on the first mechanic. When player clicks on a box, Plarc moves to that box so player controlling another box. The first approach I came up with was an idea to make a boolean variable (is_player). In a _physics_process function I needed to check the variable and if it is true to move box respectively to the player actions. Isn't it dirty? It isn't the worst way to do it but it isn't beautiful.
So I started to think how to do it more beautifully and I came up with idea to split box and Plarc (player) to two separate scenes. It sounds naturally when you know "story" that Plarc is AI that can move itself to other boxes. But how to do it? How can it be implemented with two separate scenes? Answer is - COMPOSITION :D
As I said earlier, I found that parent may not to know about child and directly interact with it. Engine calls _physics_process function for each node every physics frame so parent may not to call functions of child because Engine will do it instead... It allows you to invert relations direction. Parent won't know anything about child but child will control the parent. It is a state/strategy pattern implemented via composition.
How it looked? I just used get_parent() function in the Plarc script and set parameters for parent instead of it. When player clicks on box, I just need to move Plarc's node to a new place as a child of another box. The beautiful solution.
To give body ability to interact with color rules I just needed to put ColorBody node as a child of the node I want to live in color rules and select one of the colors. It is all. Isn't it cool?
License: CC-BY-SA 4.0