Unity: Using an FSM to control your GameObjects

Thanks to my good friend Maurizio, who’s been helping me removing the dust from my memory, today I’ll show you how to use a simple FSM to control your GameObjects šŸ™‚

First, if you don’t know what an FSM is, please read this, and maybe this too.

Done? Good. Now take a look at thisĀ (use arrows and spacebar for jumping).

See? It’s just Mario walking on a small platform. He can jump (obviously, he’s Mario) and can fall from the borders.

There are tons of ways to implement this and one of them is using an FSM.

The Player Ā and the bricks have only a BoxCollider2D, no Physics components. On the Player I have added a Script component that acts as a controller (code is on GitHub).

The idea is to let the controller initialize the FSM adding the needed States and define for each state the TransitionsĀ (basically destination State and condition ).

For this demo I have implemented three States: Default, Jumping and Falling. The transitions are simple:

FSM Transitions

  • Default -> Jump: on “spacebar” pressed
  • Default -> Falling: if no collision occurs on -Y
  • Jump -> Falling: after 0.5 seconds
  • Falling -> Default: if a collision occurs on -Y

The states themselves are pretty simple:

  • Default:Ā checks Ā for input onĀ the horizontal axis and moves the player
  • Jump: adds an impulse to the Y of the player
  • Falling: applies gravity to the player transform

XNA and Windows Form

ok, this time I’ve focused my spare time on making Windows Forms and XNA cohesist.


I’ve created a small example of how to do that and pushed everything on GitHub as the last timeĀ Ā , you can find the repository here.

Basically you have to create everything by yourself, GraphicsDevice and ServicesContainer. Yeah, that can be a mess.

Oh and don’t forget to setĀ PresentationParameters.IsFullScreen to false!

Hexagons! Hexagons everywhere!

I feel bored. Sometimes I feel so bored that I start walking around as if I were on a tiled map. And sometimes I like to switch from rectangular to hex-shaped tiles šŸ˜€

I’ve started working on a hex-based map renderer, just because, as I said. I’m bored.

Here’re the results so far:

Senza nome

And this is the tile texture:


I’m using XNA 4 (yeah I know, but that’s easy and I love to do everything by myself). Here’s part of the rendering code:

_hexTexture = this.Content.Load<Texture2D>("hex");
_hexOffset = new Vector2(_hexTexture.Width * 0.75f, -_hexTexture.Height * 0.5f);

var hexPos = Vector2.Zero;
for (int y = 0; y != 10; ++y)
 hexPos.Y = _hexTexture.Height * y * .5f;
 hexPos.X = _hexOffset.X * y;
for (int x = 0; x != 10; ++x)
 hexPos += _hexOffset;
 spriteBatch.Draw(_hexTexture, hexPos, Color.White);

Easy huh?

© 2017 Davide Guida

Theme by Anders NorenUp ↑