Technical posts

Using Command pattern to handle input in Unity and C# (Part II)

by on Nov.26, 2015, under Unity3D

<—— Using Command pattern to handle input in Unity and C# Part I

In my previous post, I was just introducing how to apply the Command design pattern to handle our game’s input (in Unity and C#). At the end of part I we came up with a simple solution to handle it, but we were still missing a “way” to adapt our code to different game scenarios (menus, in-game, … ). For example in the code I wrote there, we were assigning the A button to the fire action. But what if we are in the main menu and we just want to assign this button to accept instead of Fire? In this second part, I will try to adapt the code we developed before in order to support different game scenarios.

Let’s then first modify the base class in order to “store” the method we are supposed to call. Yes, you probably wonder by now that I am referring to C# delegates / actions. Our Command base class now will include a new Action var:

    public abstract class Command
    {
        protected Action command;

        public Command(Action _command)
        {
            command = _command;
        }

        public abstract void Execute();
    }

Once we have modified our base class, we will have to create only 1 instance or unique type of controller (or create a few different implementations, but for this example with 1 is enough). So, lets include some logic in our InputAction class to call the Action or Delegate its supposed to:

    public class InputAction : CommandBase
    {
        public InputAction(Action _command) : base(_command)
        {
        }

        public override void Execute()
        {            
            if (command != null)
            {
                command();
            }
            else
            {
                throw new NoMethodToExecute();
            }
        }
    }

As you can see in the code above, I am checking that the command variable (C# Action) is not null. This is a safety check that can be avoided to save improve performance, but of course we will need to be 100% sure it is always with a value (to avoid our game just crashing or having strange behaviours). One solution here could be to use the NullObject pattern (but this will come in some separate post). Also you can see that I am throwing a NoMethodToExecute exception. This is just a custom exception I made to handle when our command is null (source code in the github link I posted below).  So now we can create a lot of different InputActions just changing the method those ones will be calling when they will have to be executed. Let’s now modify our InputManger class to support this new functionality:

public class InputManager
{
	private Dictionary commandList;

	public InputManager()
	{            
		commandList = new Dictionary<string , InputAction>(();
	}

	public void AddControl(string _cmdName, Action _cmd)
	{
		if (commandList.ContainsKey(_cmdName))
		{
			commandList[_cmdName] = new InputAction(_cmd);
		}
		else
		{
			commandList.Add(_cmdName, new InputAction(_cmd));
		}
	}

	public void ResetControls()
	{
		commandList.Clear();
	}


	public void ExectueCmd(string _cmdName)
	{
		if (commandList.ContainsKey(_cmdName))
		{
			commandList[_cmdName].Execute();
		}
		else
		{
			throw new NoCommandToExecute();
		}

	}
}

As you can see above I am using a Dictionary (with a string as a key) to store all our events. This is not the most efficient way to store them, but for this example will do :). Basically I just create a new InputAction for all the Input we would like to handle. For example, following the 2 events we worked with in Part I (Jump and Fire) we will add them into our newly created InputManager as follows:

commandList.Add("jump", new InputAction( OnJump ));
commandList.Add("fire", new InputAction( OnFire ));

In the code above, “OnJump” and “OnFire” are the functions or methods that will handle the jump and fire logic (usually in some kind of player control).

And that’s all. With this simple implementation we will handle our game’s input using the command pattern. I will be writing part III sometime in the future as we will need an “Undo” operation in Dimension Drive. This type of operation is easily implemented with the Command pattern as well. It is also really good to save all the commands your game is handling so you can “easily” implement a “replay” or ghost mode. But let’s not spoil all the fun as probably that will have a big impact in Dimension Drive (the game I am working on right now). If you want to access the source code of this post so far (including a Unity example on how to use it), please see in my github public repository here.

Leave a Comment more...

Using Command pattern to handle input in Unity and C# (Part I )

by on Nov.24, 2015, under Unity3D

Definitely Command is one of my favorites patterns. It is present in most of my games code-base. When used in the right place will help you to achieve encapsulation of your Input -> Action code.  Let’s see first how the “Gang of four” define this pattern:

Encapsulate a request as an object, thereby letting users parametrize clients with different requests, queue or log requests, and support undoable operations.

As you can see that definition is just … obscure? (I can’t find the right words for it). Well for all non-native English speakers (as myself) I would find that sentence a bit difficult to understand at first. “Encapsulate a request as an object” we all can agree that is referring to and object oriented encapsulation of callbacks (or at least kind of). With “Letting users parametrize clients with different request” we can assume that is referring to the ability to use the objects mentioned before to perform different actions. Then finally the rest is just a list of things you can do with this pattern.

Let’s now get down to business. In all games, or at least 99,9999% of them, there is a place where the code reads the user input (game pad, keyboard, touch screen, …). Once this input is received, translates this information into a game action, for our example let’s say jump and fire:

control

(continue reading…)

Leave a Comment :, , more...

How to add a CCLayer with transition effect in current running CCScene

by on Mar.05, 2014, under Cocos2d-x, Technical posts

Let’s imagine that in our current running scene we would like to show a new control. For example a new window (box) containing a menu option, or some new information we would like to display. We can just build and place it in the screen, but this could be a bit boring. I will try in this post to add a new layer containing the mentioned control using some transition effects. The same kind of effects that you can use when replacing the current scene with a new one. So let’s try to accomplish this “kind of” transition effect. (continue reading…)

Leave a Comment more...

How to create & write a CCDictionry into a file in cocos2d-x and c++

by on Jan.03, 2014, under Cocos2d-x, Technical posts

Imagine the following scenario in your game development process: sooner or later you will need to store some information in order to load it again next time the player would like to play. In this project I will need to store some simple game player information as number of levels played, levels succeeded, time used to complete them, points win, …. and few more variables. As you can see, they are just a few variables, so using solutions as SQLlitte3 could be maybe too much. (continue reading…)

8 Comments more...

Customized Timer Control in cocos2d-x

by on Dec.16, 2013, under Cocos2d-x, Technical posts

Lately I came across in my cocos2d-x project (this) with the need of creating a Timer Control. I wanted to display the time using the following format: mm’:ss’ (inside this timer control). Also I wanted the text to become yellow or red after a period of time (even blinking when displaying red color).

I decided to create a control extending CCNode and containing 2 CCLabelTTF objects. Using 1 for displaying minutes (00′) and another one for displaying seconds (:00”). Summarizing this new extended control will have the following behavior: (continue reading…)

2 Comments more...

Extending CCProgressTimer to use different sprites depending on percentage value

by on Nov.14, 2013, under Cocos2d-x, Technical posts

I have developed a little extension for CCProgressTimer control in cocos2d-x. I needed to use different images (sprites) for my progress bar depending on the percentage, and I did not want to enter that code into my Scene’s code. Let’s Imagine the following case:

We have a progress bar and we would like to use a different CCSprite depending on the percentage. For example a green bar when the values are between 25%-100%. Then when below 25% an orange bar (or even more, a different one for each 25% block). Of course we can control this using a simple “if” statement in our “update” logic. But as our game’s code size would increase, it could be a bit messy. I decided to create an extension from CCProgressTimer. It works in a way that every time we assign a new “setPercentage”, it will check which sprite is supposed to use. Having stored previously all sprites in std::map, including the percentages in which that sprite shall be used. (continue reading…)

Leave a Comment more...

How to use a progress bar in cocos2d-x and C++

by on Jun.14, 2013, under Cocos2d-x, Technical posts

Sometimes in our games we need to add a progress bar. We can use it to show the remaining fuel of a starship, car, … . We can also use it to show the loading progress between two different scenes, loading a new level, … . There are few examples out there on how to do it, but they are mainly for the Iphone version of Cocos2d-x. I would like to share with you how I build mine to show the remaining fuel of our balloon. (continue reading…)

Leave a Comment more...

How to create a Menu in Cocos2d-x using Sprites Sheets

by on May.21, 2013, under Cocos2d-x, Technical posts

I would like to write a post about how to use a texture sheet and a CCMenu object together. In other words, use a single image as a container with all our menu single images. This technique is called “texture sheets”, and is one of the features available in cocos2d-x that will make our games easy to develop. Using a single image for all textures will make this process easy to manage, and better handled by our mobile device graphics card. (continue reading…)

13 Comments more...

How to force an object to stay in the visible camera area in Unity

by on Mar.10, 2013, under Technical posts, Unity3D

Imagine that you are developing certain game that needs an object to stay in the camera’s visible area. For example a vertical space shooter where we would like to have our space ship to stay all the time in the visible area.

Let’s imagine that our player is free to move the space ship all around the screen, shooting enemies, collecting items, etc. Of course we would like to force our player to stay within the game screen when approaching the borders. As there are many devices with different screen resolutions, will make impossible to handle all of them manually. Then our first step will be get the screen resolution in order to calculate the borders. Let us say for this example that the player will be able to go maximum till 5% off the horizontal border and 10% off the vertical border.

(continue reading…)

3 Comments more...

How to load a cocos2d-x plist (configuration file) from C++

by on Jan.14, 2013, under Cocos2d-x

In this post I will try to explain how to use this cocos2d-x functionality from our C++ code.

Sometimes we might need to load a configuration file with some information for our game. For instance, let’s imagine that we need to load the level background image file name, width and height. Of course we always can use a constant, local class var, … etc to store this information. But as your project grows, it will be difficult to remember where you have stored this var, or the name of it. To avoid it, a solution could be to store this information into a text file. Cocos2d-x provides a functionality for loading a XML “like” text file.

(continue reading…)

4 Comments more...