Posted January 05, 2022 by Kate Killick
I started a prototype to explore mechanical possibilities with cogs and gears. I’m not sure exactly where it’s going, so I wanted to create a little playground where I can drag and drop cogs of different sizes to create a chain.
The cogs would turn wheels with gaps in (I'll call those "pie wheels"), so it would be possible to drop a ball into the top and drop it down through the system. The player can use the left/right arrows to control the rotational direction of the system.
Starting functionality:
First logic attempt
The first challenge was understanding how a cog can know which cog is its parent, and therefore which way it should turn. This would be simple if each cog only had one parent cog and one child cog, but this felt like an artificial restriction. I wanted the player to have the freedom to create branches and loops.
The rule:
This sounds quite simple, but took me a while to figure out correctly. My first method was to try to keep each cog self-contained, only knowing about the cogs it was touching, but with no concept of its overall place in the chain. It worked initially, but I got stuck in an infinite loop when the player took out and replaced a middle cog in the chain. Perhaps someone with a better understanding of recursion could solve it, but I opted to change my method.
The end method
I found my solution by having a single manager script for all the cogs, which evaluates the chain any time it changes and assigns info to the cogs. It begins by looking at all the cogs colliding with the starter cog and assigning those a “chain index” of 1, and then loops through their colliding cogs and assigns them a “2”, etc. It also tells each cog who its parent is, and the rotational direction it should take. If it finds a cog that already has a chain index assigned, we know we are in a loop of cogs. It checks that all the colliding cogs are trying to turn it in the same direction, and if not it decides the system is jammed.
I added the ball spawning, and the end result can be seen in the screenshot gifs.