How to create collidable curves (trail, lines, whatever) in Unity3D

Halloweee screenshot
Halloweee! Pumpkins and candies for a Halloween game (Android, free)

A few weeks before Halloween we decided to create a minigame to polish and learn new tricks (and treats, ha!). With not much time left for the game, we came up with simple mechanics: pumpkins fall from the top of the screen and must land safely. If pumpkins fall too fast they break and don’t score. By drawing a line (which would look like a spiderweb), players guide healthy pumpkins gently to the ground while throwing rotten pumpkins away.  Both actions score points. The goal consists just on getting as many points as posible in 64 seconds. We called it Halloweee! and it finally looked like you see on the image (you may try it on Android, it’s free)

The trickiest part was how to create a collidable and properly textured curve from a gesture drawn by the player. Thanks to Unity’s Mesh class it was not that hard.

Continue reading

Autómata finito en C# para Unity3D

Este artículo es una traducción del que escribimos originalmente en Inglés.

Los Autómatas Finitos o  Máquinas de Estado Finito (FSMs en sus siglas en Inglés) son bastante útiles en contextos muy diversos, como probablemente ya sabrás si estás leyendo ésto. Desde el menú al comportamiento complejo de las entidades de un juego, una buena FSM puede mejorar la legibilidad de tu código y simplificar el diseño. O convertirlo en un infierno de código espaguetti, dependiendo de cómo se implemente…

Continue reading

Shuffling C# generic lists

Just a quick hack for shuffling generic lists in C# like this one:

List<T> list

You may use proper solutions like those in this StackOverflow thread, if you need it for something serious, or simply do this:

list.Sort ((x, y) => Random.value < 0.5f ? -1 : 1)

which simply defines a sorting function that randomly returns -1 or 1 when comparing two elements, shuffling the original list.

I’m not exactly sure if this is right, but it works! If there’s a reason why this is not a good idea, please share it!

Simple FSM-like structure using Coroutines in C# (Unity3D)

The previous post got a funny comment in Reddit: “Yawn. Hang on, inheritance, singletons? Bletch”. So I thought… “I may be getting rusty… let’s give those coroutines a try”. At first, coroutines seemed like a sure way of leaving behind all my (humble) OOP practices.  I though they were some kind of goto statement, probably because I had never given them a try. Ignorance is bold.

So here’s the same Miner from our previous post (yes, the one from Programming Game AI by Examples), going back and forth from the mine to the bank. But this time, each state is implemented using a coroutine. Thanks to the yield statement, coroutines can simulate our three state stages: Enter, Execute and Exit. Even better, we may easily add pauses wherever we need. If the coroutine is used to implement an entity’s AI, it can be updated every x milliseconds (depending, for example, on the entity’s reflexes), instead of every frame.

The trick lies in the FSM coroutine:

 IEnumerator FSM() {
    // Execute the current coroutine (state)
    while (true)
	yield return StartCoroutine(state.ToString());

It constantly calls and waits for the execution of the current state (which is another coroutine). If the executed state changes the current state, the next iteration will launch it properly. I guess some code should be added to change states in external events, stopping any running coroutines.

So here we go! I’ve removed some variables, but it’s mostly the same behaviour:

File: CoMiner.cs

using UnityEngine;
using System.Collections;

public class CoMiner : MonoBehaviour {
  public enum State {

  public State state;

  public void Awake() {
    state = State.EnterMineAndDigForNuggets;

    // Start the Finite State Machine

  IEnumerator FSM() {
    // Execute the current coroutine (state)
    while (true)
	yield return StartCoroutine(state.ToString());

  IEnumerator EnterMineAndDigForNuggets() {
    /* This part works as the Enter function
    of the previous post (it's optional) */

    print("Entering the mine...");
    yield return null;

    /* Now we enter in the Execute part of a state
    which will be usually inside a while - yield block */

    bool dig = true;
    int digged = 0;
    while (dig) {
      print("Digging... " + (digged++) + " " + Time.time);
      if (digged == 2) dig = false;
      yield return new WaitForSeconds(1);

    /* And finally do something before leaving
    the state (optional too) and starting a new one */

    print ("Exiting the mine...");
    state = State.EnterBankAndDepositGold;

  IEnumerator EnterBankAndDepositGold() {
    print ("Entering the bank...");
    yield return null;

    bool queing = true;
    float t = Time.time;
    while (queing) {
      print ("waiting...");
      if (Time.time - t > 5) queing = false;
      yield return new WaitForSeconds(1);

    print ("Leaving the bank a little bit richer...");
    state = State.EnterMineAndDigForNuggets;

This way, each class contains it’s own FSM-like structure, though a simple one. No need for multiple files for each state, which can be cumbersome if a project grows (and they always do). And its really easy to follow and understand, once you understand how coroutines work.

It is a simpler solution, but pretty useful indeed! And of course, it can be combined with good OOP practices, not exactly as shown before 🙂