You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: book/state.markdown
+8-3Lines changed: 8 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -335,12 +335,17 @@ one heroine, but if we try to add two-player co-op and have two heroines on
335
335
screen at the same time, we'll have problems.
336
336
337
337
In that case, we have to <spanname="fragment">create</span> a state
338
-
object when we transition to it, like:
338
+
object when we transition to it. This lets each FSM have its own instance of the state. Of course, if we're allocating a *new* state, that means we need to free the *current* one. We have to be careful here, since the code that's triggering the change is in a method in the current state. We don't want to delete `this` out from under ourselves.
339
+
340
+
Instead, we'll allow `handleInput()` in `HeroineState` to optionally return a new state. When it does, `Heroine` will delete the old one and swap in the new one, like so:
341
+
342
+
^code swap-instance
343
+
344
+
That way, we don't delete the previous state until we've returned from its method. Now, the standing state can transition to ducking by creating a new instance:
339
345
340
346
^code duck
341
347
342
-
This lets each FSM have its own instance of the state. When I can, I prefer to
343
-
use static states since they don't burn memory and CPU cycles allocating objects
348
+
When I can, I prefer to use static states since they don't burn memory and CPU cycles allocating objects
344
349
each state change. For states that are more, uh, *stateful*, though, this is the
object when we transition to it. This lets each FSM have its own instance of the state. Of course, if we’re allocating a <em>new</em> state, that means we need to free the <em>current</em> one. We have to be careful here, since the code that’s triggering the change is in a method in the current state. We don’t want to delete <code>this</code> out from under ourselves.</p>
551
+
<p>Instead, we’ll allow <code>handleInput()</code> in <code>HeroineState</code> to optionally return a new state. When it does, <code>Heroine</code> will delete the old one and swap in the new one, like so:</p>
<p>That way, we don’t delete the previous state until we’ve returned from its method. Now, the standing state can transition to ducking by creating a new instance:</p>
0 commit comments