Protect Your Plant -- State Machines

State Machines

Posted January 12 2022, 10:10 PM

State Machines are lovely.

That wasn't supposed to be a revelation, considering that I've been in tech for like seven years now, but Protect Your Plant is actually the first time I've built real state machines to solve a problem I personally cared about, and man, they are a lot better than the jumble of code I was using before!

Oh there were plenty of things in the game that tracked their state in one way or another. State adjacent. I was in the vicinity of state machines. But once you're trying to make AI path around, follow routines, and adjust their behavior based on their surroundings, it's time to stop trying to kludge your way through problems ("Why are you moving and sleeping at the same time cat!?") and learn something new.

At this point, I've used them to make a cat, squirrels, and rabbits, who I believe take the dubious honor of being the first true enemies in the game. (If you sit still too long while a bunny can see you, it will decide your plant looks tasty, path towards you, and start nibbling on it. All you have to do to make them stop or prevent the attack is move, and you'll startle them into running away, but if that's not gameplay then I know even less about what I'm doing than I think I do.)

I'm now starting to think about making humans, and the range of additional behaviors I can simulate, the routines I can apply, and the freedom this set of tools provides. Previously I'd only set up my friendly AIs on tracks, using carefully planned schedules and timers to path them to different points and change their animations. Each one was a tiny clockwork automoton. Now I can just give them a set of times and locations and activities to perform at those locations and let them get to it. I can tell them what to interact with, and if it crosses their path, they'll do it without me carefully planning and choreographing it for them.

State Machines are good, is what I'm saying.

The above was a note from after I finished fixing the rabbit code. I'd had a bunch of revelations at that point, as I'd done many things wrong, and had gotten especially tangled in Godot's editor for awhile, but that is unfortunately far enough back in the past that I don't remember it well enough to document here. I do plan to start using this blog to document the tech side of things, hurdles and setbacks, in addition to the milestones for the game I've been recording.

Video of the critters to follow.