Tutorials containing the tag "state machines"



State Machines and Boss Fights

Posted by fariel on 03/12/17 3:31 PM


c#

Ever seen a really awesome boss fight and asked yourself "how did they do that?" Perhaps you've had a great idea for a boss and don't know where to begin programming it. Well, today I'm going to talk about how we use simple state machines in our enemies and boss fights to give believable and predictable behaviours to our favorite things to make. 

So, what is a state machine? Google defines it as "a device that can be in one of a set number of stable conditions depending on its previous condition and on the present values of its inputs." What this means is that a state machine has a series of states, or in our case behaviors, that it can switch between. For example, we might call our state machine "Boss" and its states will be "FirstAttack," "SecondAttack," and "Move."

Since this example is going to be based in Unity, we're going to use C# to show you how to write your own state machine behaviour for whatever you want. The first thing you need is an enumeration, which uses the enum type. Enumerations are, quite literally, just a list of data with names. You can find out more about enumerations in C# by clicking this sentence.

enum BossState {
    FirstAttack,
    SecondAttack,
    Move,
    COUNT
}

This creates an enum named BossState that can have values equal to FirstAttack, SecondAttack, and Move. You might notice that the last option in the enum is "COUNT." So long as COUNT is the last option in the enum, its value will be how long the enum is. This will let us select a random one later. The rest of these will be our states later on. The next piece of this puzzle is to add a variable to hold the current state of our state machine.

BossState currentState = BossState.Move;

Now we have everything we need to start and control our state machine...

Read More