Search

Tuesday, October 8, 2013

How to make 2D game


What is Unity3D?
Unity3D is an engine to create and build game to many platforms such as PC, Android, iOS and else. It can reduce a time and work in multiple platform publishing. We can design and create game object inside editor (move, rotate and scale) easily with visualize editor. Every content and parameter that we need to see or adjust are built in visualization user interface. Also many components such as physics, audio, camera and else are already build-in in the Unity3D. So Unity3D design for every people who interest to make game, this application is very good when you cooperate with other people such as programmer or artist because the same project can be work on different platform, regardless of Windows or iOS. Unity also provide asset store, to let user share script, model or extension via online market. We also can sell our asset product in Unity asset store.


Is it possible to make 2D game in Unity?
Yes, it is possible but it might be painful to apply 3D game technique in 2D game. First of all, you can set camera projection to orthographic and now everything will look like 2D game.



Suggested tools to make 2D game
NGUI
NGUI is an extension in Unity asset store. As its name, it use for manage user interface. We can create background, label, image button, and progress bar by just only one click on NGUI interface. They actually can set animation tween to each widget. For example, if you create image button, you need to specify background image for button, text label and if you want to add more animation effect such as scale up on hover, then you just add component into that image button.
2D Toolkit
2D Toolkit is also an extension that you need to buy from Unity asset store. It use for create 2d sprite and animation. You need not to write you own code to run texture frame by frame because 2D toolkit has provide user interface to drag and drop texture into sprite collection and we can create sprite animation by using the sprite collection.
iTween & iTween Visualization Editor
iTween is a free extension on Unity asset store. We can also use iTween Visualization Editor which is an extension on top of iTween, which make us need not to write code. The iTween extension has many cool features such as moving, rotating, scaling, shaking and so on.






How to download and use these tools in our game

NGUI - Download
New version of NGUI is not free.
Fortunately NGUI also provide free version to us, but it is the old version (NGUI 2.0.7c).
If you download new NGUI version from asset store, the editor will automatically extract NGUI into your project but if you download free version. You need to open your current Unity project and double click on unity package file. It will extract NGUI package into your current project. After you finish extract NGUI package, you will see NGUI menu on menu bar.
NGUI - Usage
  1. Click NGUI menu and choose Create a New UI
  2. Select a layer that 2D camera will able to see, and click Create Your UI
  3. You will get UI Root (2D) game object, if you expand Anchor game object, there is a Panel game object inside which you can create and put widget here.
  4. Simply, please click at panel game object
  5. Click NGUI menu and choose Create a Widget
  6. Choose Atlas, the Atlas we can create by Atlas Maker which stay inside NGUI menu
  7. Choose Font, the Font we can create by Font Maker which stay inside NGUI menu
  8. Choose Template as you want
  9. Then click “Add to” button



2D Toolkit - Download
2D Toolkit is not free, you have to buy from Unity asset store
After you download from asset store, it will automatically extract to your project. Then you will see 2D Toolkit menu.
Figure 1
Figure 2


You can create 2D sprite or 2D animated sprite object via this menu list but you have to create sprite collection. The following steps below is the way to create it.


2D Toolkit - Usage
  1. Create sprite collection folder

  2. Right click at the folder and choose create, then go to tk2d and click sprite collection
     


  1. Rename your sprite collection and click “Open Editor…” button
     


  1. Select all textures that you want to use
     


  1. Drag and drop the textures into Sprite Collection panel and click “Commit” button
     




iTween & iTween Visual Editor - Download
Download Unity package and extract into your project
 
iTween & iTween Visual Editor - Usage

  1. Create game object
  2. Add iTween Event component



  1. Choose Event Type as you want
  2. Adjust parameter, make it work perfectly as you want 

     

Scripting
Suggested programming architecture
The suitable programming architecture for Unity is one main class hold a bunch of manager objects. One manager will be responsible for one task such as input, audio, scene and so on. Each manager must implement Singleton design pattern to prevent multiple object initialization. We also apply Façade design pattern to make manager class use easily as much as possible.

 



Manager class make you easily control game system
You should apply Singleton design pattern in manager class because we want to ensure that every parts of program access the resource via this class. We may provide public static instance property in manager class which other class can call method like this “Audio.Instance.PlaySound(soundEffect)” and Main class must be the class who initialize every manager objects. Any manager objects can be access via Main instance or their own public static instance property.


Example - Main.cs
using EnityEngine;
public class Main : MonoBehavior {
    public static Main Instance {
        get {
            if (_instance == null) {
                GameObject gameObj = new GameObject(“Main”);
                _instance = gameObject.AddComponent<Main>();
            }
            Return _instance;
        }
        private set;
    }
    public AudioManager Audio {
        get;
        private set;
    }
    private static Main _instance;


    private void Awake() {
        _instance = this;
        Audio = AddComponent<AudioManager>();
       
        DontDestroyOnLoad(gameObject);
}


}


Example - AudioManager.cs
using UnityEngine;
public class AudioManager : MonoBahavior {
    public static AudioManager Instance {
        get {
            if (_instance == null) {
                _instance = Main.Instance.Audio;
            }
            return _instance;
        }
        private set;
    }


    Private static AudioManager _instance;


    private void Awake() {
        _instance = this;
    }


    public void PlaySound(SoundEffectType soundEffectType) {
        // Play sound
    }


}


If you notice the code, you will see if an audio instance does not initialize yet, it will initialize from Main class. Which now we can ensure that both Main and Audio class are instantiated. The question is why we need to do like this. The reason is in debugging mode, we may doesn’t come from main scene, and Main instance didn’t instantiate which it holds some significant information. So this way will help you initialize Main instance properly when Manager’s function have been called.

Template class make you develop game quickly
If you have been developed Unity game with a ton of scene and some scene there are some little slightly different. For example, there are three similar scenes which game actions are the same but the different is just minor content inside each scene. Do we have to write three classes separately in each scene or it can be done by one class with configurable variable? As we know that Unity has inspector which show every serialize fields. We can use this feature to minimize our work. It is better when you encounter with some bugs in one of those three scene, we can solve the problem directly at one place and other two scenes will be solved too. You need not to fix every scripts.

Summary 

The good design will make you easily extend your code functionality and quickly finish your project.

Tuesday, October 1, 2013

Switching from Synchronous to Asynchronous

Recently, we decided to switch from Python/Django to Node.js/Express due to the customer requirement. This required a huge change in design paradigm for us: a switch from synchronous programming to asynchronous programming. In synchronous, you have to wait for the previous command to be completed before the next command is executed. In asynchronous way, the next command can be executed without blocking from long running command. The style of coding have to be changed. Callback function becomes important role to let you know that the long running command has been finished.

Asynchronous VS Synchronous

Synchronous ensures the sequence of the command execution. The next command will not be executed unless the previous one is finished.

var data = dbCall();
returnData(data);

If dbCall is synchronous method to connect to database to get the data, returnData is blocked and have to wait until dbCall is finished and return data.

Asynchronous is non-blocking, the application can run the next command while waiting for the previous command to be finished. This is very useful for application with long running command like I/O execution. Let’s see the previous example.

var data = dbCall();
returnData(data);

Suppose that dbCall is asynchronous method which connect to database and get the data. The function returnData will be executed immediately after calling dbCall no matter the dbCall is finished or not. This will be the problem since returnData is supposed to send the data returned from dbCall but data may not be assigned. What if we want to ensure that the previous command is finished before running the next one in order, callback takes important role for this. In this case, callback function is passed as a parameter to dbCall and called back after the asynchronous function is finished.

var callback = function(data){
returnData(data);
};
dbCall(callback);

The function dbCalled should look something similar to this.

var dbCall = function(callback){
// connect to database and get data
// this is executed asynchronously
// and do callback after getting data
db.getData().success(function(data)){
callback(data);
}
};

The callback function is called when dbCall got the data.

If the function returnData takes the same parameter as the callback function we can simply modify the code to be more simple.

dbCall(returnData);

Frontend developers may be used to asynchronous paradigm already since a lot of web development is event driven. Users trigger the event to execute the function. The very simple example is the JQuery on change event.

$('input').change(function(){
 alert('The text has been changed.');
});

There is no looping to wait for the input the be changed but the function is trigger when the change event occur.
Another example is ajax request.

$.ajax({
url: '/ajax',
type: 'GET',
done: function(res){
alert(res);
},
fail: function(){
alert('error');
}
});

Done represents the callback function to be called when it successes, while fail represents the callback function to be called when error occurs.



Introduction to Node.js


Node.js is a JavaScript platform that allow you to run JavaScript code in the backend. It builds on Google’s V8 which is Chrome’s JavaScript runtime.

The following code is the simple web server run at port 8080 written in Node.js.

var http = require('http');
http.createServer(function (request, response) {
 response.writeHead(200, {'Content-Type': 'text/plain'});
 response.end('Hello World');
}).listen(8080);

The function createServer is asynchronous function which will return a newly created web server object and add the anonymous callback function(request listener) to the request event.

The code can be executed using node command from command line.

node sample.js

It will return “Hello World” to the browser when you request for http://localhost:8080.

For more information about Node.js, please visit Node.js official website.


JavaScript Closure


Closure is one of the most frequently used features in JavaScript. It allows an inner function to access the variables and parameters of the outer function.

function outer(a){
var b = 5;
function inner(){
console.log(a+b);
}
inner();
}

The inner function can access the parameter(a) and variable of the outer function. When you call outer(3), it will print 8 to the console.

> outer(3)
8

Be careful of having closure in a loop. Since the outer function pass the variable by reference, the variable of the outer function can be change from time to time. This can cause the problem since we will never know when the command line that uses the outer variable is executed. It is not guaranteed that the value is the value that we expected by the time it is executed.

function doLoop(){
for(var i=0;i<5 i="" span="">
setTimeout(function(){
console.log(i)
}, 100)
}
}

From the example above, the next loop is executed immediately after the setTimeout function is called. This causes the variable i to be changed to 5 by the time it is printed in the inner function. The output is “5” printed 5 times to the console which is what not we expect.

Since javascript variable scope is in function scope, we can avoid this error by wrapping the function and pass the parameter to the function instead.

var doSomething = function(i){
setTimeout(function(){
console.log(i)
}, 100)
}
function doLoop(){
for(var i=0;i<5 i="" span="">
doSomething(i);
}
}

When we run doLoop() from the code above, the output will be as expected.
0
1
2
3
4


Since this is our first project in Node.js, we have faced a lot of problem in the beginning. This let us learn a lot and gain experiences in different aspects especially to think and design in asynchronous way as well as to have better understanding of callback function and closure too. Since these are different approaches, it depends on how you application works.If your application requires a lot of long running commands like I/O tasks, asynchronous will allow your application to handle something else while waiting for the background task which can be more utilized without blocking. Otherwise, as my own opinion, synchronous programming have simpler structure.