Showing posts with label GuayScript. Show all posts
Showing posts with label GuayScript. Show all posts

0 Hansel Script

This is one of the first (if not the first) script I wrote using GuayScript instead of MonoBehavior. It wasn't created for anything in particular, but it'll surely end up being part of some enemy's behavior.

It keeps track of its GameObject position, and will send a notification every time it's has traveled a certain distance. The interesting part about it it's that it shows how notifications can be edited by the level designer for maximum flexibility.

/// <summary>
/// Hansel script will drop a pebble (trigger an event) whenever a certain distance has been covered
/// </summary>
public class HanselScript : GuayScript
{
    /// <summary>
    /// Distance between pebbles
    /// </summary>
    public float DistBetweenPebbles;
 
    /// <summary>
    /// Event notified everytime the distance is covered
    /// </summary>
    public Notification DropPebbleEvent = "pebbleDropped";
 
    /// <summary>
    /// Ctor,
    /// </summary>
    public HanselScript()
    {
        var lastPosition = new Vector3();
        var accDistance = 0f;
 
        OnAwake  = _properties => lastPosition = GameObject.transform.position;
        
        OnUpdate = _deltaTime =>
        {
            accDistance += (GameObject.transform.position - lastPosition).magnitude;
 
            ifaccDistance >= DistBetweenPebbles )
            {
                accDistance -= DistBetweenPebbles;
                NotifyDropPebbleEvent );
            }
 
            lastPosition = GameObject.transform.position;
        };
    }
}

0 The Message System

Messaging is at the core of any component-based system. Rather than directly calling other component's methods, you send messages to a postal address instead. If there happens to be a component listening to these messages from that address, it will receive them.

All this functionality is offered by the PostOffice class. This class works at a very low level. It doesn't know about the Guay Framework or Unity. It just knows about addresses and message ids.

To listen to a specific message, you provide an address, a message identifier and a message callback. The callback will be called whenever someone sends that message to that address.
public void Subscribe( object _address, string _message, MessageCallback _callback )
{
    ....
}

Likewise, to send a message you call the following method specifying an address, a message id and a list of parameters:
public void Send( object _address, string _message, params object[] _params )
{
    ...
}

You can also can broadcast a message through the method:
public void Broadcast( string _message, params object[] _params )
{
    ...
}

Let's see an example:
public class Player
{
    public Player()
    {
        ExampleApp.PostOffice.Subscribe( 
            "gameAddress",
            "gameStart",
            ( _event_params ) =>
            {
                Debug.WriteLine"The game has started!!" );
            } );
    }
}
 
public class Game
{
    public void Start()
    {
        ExampleApp.PostOffice.Send"gameAddress""gameStart" );
    }
}
 
public class ExampleApp
{
    private static PostOffice mPostOffice;
    
    /// <summary>
    /// Retrieves the post office
    /// </summary>
    public static PostOffice PostOffice
    {
        get { return mPostOffice ?? (mPostOffice = new PostOfficefalse )); }
    }
 
    public ExampleApp()
    {
        // a game is created
        var game = new Game();
        
        // player is created. it will subscribe to the "gameStart" message
        var player = new Player();
        
        // the game starts, sending the "gameStart" message to the address "gameAddress",
        // the message will be queued.
        game.Start();
    }
 
    public void Update()
    {
        // once per frame, the post office is updated, delivering all queued messages.
        // Player will get the "gameStart" message
        PostOffice.Update();
    }
}

This example shows what working with the typical message system looks like. However, this class is not directly exposed to the game code. Instead, the Guay Framework makes use of the PostOffice class internally, presenting a Unity-friendly interface which makes messaging really easy to use from scripts. You can find more information about this in the description of the GuayScript script.


0 The Guay Framework explained

I'm preparing a series of articles about each of the important aspects of the Guay Framework, namely:
  • The messaging system.
  • The GuayScript.
  • Sending/receiving messages.
  • Dynamic Properties.
These form the core of the framework. I think they cover most of the aspects you'd expect to find in a component-based system. Keep in mind that it's still a work in progress, so some things could eventually change from one day to the next (though it's not likely). I'll try to maintain articles as concise as I can since my intention is not to bore people explaining every class or method (unless I'm asked otherwise), but to explain the rationale behind. I'll include code snippets where I feel it's needed.


0 A quick glance at GuayScript

GuayScript is the of the central piecea of the Guay Framework. Its main goal is to provide your scripts a clean and very intuitive API to interface with a real component-based environment. The example below shows how simple is to communicate with the system. There's no need of looking for specific components, thus avoiding the creation of ugly dependencies.

I'll explain it all in detail in future posts.

Example of a typical GuayScript script
    //
    // Health script. Makes a GameObject to have 'life'
    // 'Implements' the HealthInterface interface
    //
    public class Health : GuayScript
    {
        GameObject OtherGameObject;
        public float MaxCapacity;
        public float Amount;

        public Health()
        {
            var dead = false;
            var currentHealth = Amount;

            OnAwake = _properties =>
            {
                Messages[ HealthInterface.CmdIncrease ] = ( _id, _args ) => currentHealth += _args.Get();
                Messages[ HealthInterface.CmdDecrease ] = ( _id, _args ) => currentHealth -= _args.Get();
                Messages[ HealthInterface.CmdRefill   ] = ( _id, _args ) => currentHealth = MaxCapacity;
                Messages[ HealthInterface.CmdDie      ] = ( _id, _args ) => currentHealth = 0;
            };

            OnUpdate = _deltaTime =>
            {
                if( dead )
                    return;

                if( currentHealth <= 0 )
                {
                    dead = true;

                    // components say interesting things through the Notify function 
                    Notify( HealthInterface.EvDead );

                    // components can also say interesting things to other objects
                    OtherGameObject.Send( HealthInterface.EvDead );
                }
            };

        }
    }