Saturday, November 7, 2015

FPS (Frames Per Second)

Computing FPS value is pretty important. When the game is tested on target hardware (especially on devices like Samsung TVs) we need to know exactly that value.

I am using following C# script assigned to the empty game object. I simply count number Update() method calls and every second I update the FPS value and I log it.
public class Fps : MonoBehaviour
{
 // Update interval is 1 second
 const float UPDATE_INTERVAL_1SEC = 1.0f;
 
 // Frames drawn over the interval
 private int frames  = 0;
 
 // Left time for current interval
 private float timeLeft;
 
 // Is the debug mode enabled?
 public bool debugEnabled = true;

 // FPS
 private int fps = -1;
 public int GetFps
 {
  get
  {
   return fps;
  }
 }
 
 void Start()
 {
  timeLeft = UPDATE_INTERVAL_1SEC;
 }

 void Update()
 {
  if ( debugEnabled )
  {
   // Decrease the time
   timeLeft -= Time.deltaTime;
   
   // Increase number of frames
   frames++;
   
   if( timeLeft <= 0.0 )
   {
    fps = frames;      
    timeLeft += UPDATE_INTERVAL_1SEC;
    frames = 0;
    Debug.Log ("[Fps]:[Update] === FPS: " + fps +"("+Time.time+")" );
   }
  }
 }
}

Friday, November 6, 2015

Yield bogeyman 2/2

This is second part of a blog, in which I am trying to explain yield keyword and its use in Unity. The first part is there.

In Unity we usually execute majority of the code every frame in Update() calls. However sometimes we need to do actions in defined interval (e.g. every second) or at some exact time after user starts the game level.

For that purpose we use something Unity calls coroutine. We already know that using yield keyword we could execute a method, return from it preserving its state between calls and continue the method execution later. A coroutine is using the yield keyword to do exactly the same - pause execution, return control to Unity and continue later where it was left.

For testing purposes let's define a coroutine with the endless while loop. Note that in Unity the coroutine needs to be started by using the StartCoroutine() method call:
void Start () 
{
 StartCoroutine(TestCoroutine());
}

void Update () 
{
 Debug.Log("[CoroutineTest]:[Update] Time: " + Time.deltaTime );
}


IEnumerator TestCoroutine()
{
 while (true)
 {
  yield return 1;
  Debug.Log("[CoroutineTest]:[TestCoroutine] Time: " + Time.deltaTime );
 }
}
After you will execute the code, you will notice from console logs that the Update() and Log() functions are called with the same frequency - i.e. the execution of the coroutine is resumed every frame. Using corountines that way might be useful in some cases because it allows easy dividing of standard methods to its parts called periodically every frame, but it is not what we want to achieve now: We want to call coroutine regularly at defined interval - one second in our case.

For that purpose Unity has the special class called WaitForSecondsUsing that class (It can only be used with a yield statement in coroutine.) we are able to suspend a coroutine for the given amount of seconds. The modified code is below:
void Start () 
{
 StartCoroutine(TestCoroutine());
}

void Update () 
{
 Debug.Log("[CoroutineTest]:[Update] Time: " + Time.deltaTime );
}


IEnumerator TestCoroutine()
{
 while (true)
 {
  yield return new WaitForSeconds(1);
  Debug.Log("[CoroutineTest]:[TestCoroutine] Time: " + Time.time );
 }
}
In console logs you will see that the TestCoroutine() method is called approximatelly every second:
...
[CoroutineTest]:[Update] Time: 0.005466057
[CoroutineTest]:[Update] Time: 0.00672265
[CoroutineTest]:[TestCoroutine] Time: 2.003362
[CoroutineTest]:[Update] Time: 0.004957338
[CoroutineTest]:[Update] Time: 0.005276212
...
[CoroutineTest]:[TestCoroutine] Time: 3.006917
...

Thursday, November 5, 2015

Parallax scrolling

Repeating background (tiling)

There are several ways how to create parallax scrolling. I was using different approach until I found that following one is the best:
  1. Use the Quad 3D game object
  2. Create Material:
     a. Material's shader needs to be set as Mobile>Particles>Alpha Blended
     b. Texture placed over the material needs to have Wrap Mode set to Repeat
  3. Attach the material to the quad
Quad with material
In the next step create a script and based on the screen width:
  1. We compute the tiling parameter, i.e. how many times the texture on the material has to repeat horizontally to cover the whole screen width.
  2. We have to resize the quad so repeating texture can fit it precisely (tiling parameter * texture width). Note that I am using for the game the ratio 1 pixel = 1 game unit and I force the screen resolution to be always 360px height with computed width based on the screen aspect ratio. The computed width has almost always the same value 640px, since most TV screens are 16:9. The code looks like the one below:

// How many textures are per screen width
float count = Mathf.Ceil ( Screen.width / render.material.mainTexture.width / MyScreen.pixelsToUnits );

// Set the new size to the quad
transform.localScale = new Vector3(count * render.material.mainTexture.width, transform.localScale.y, 1);

// Set the tiling parameter of the material
render.material.mainTextureScale = new Vector2(count, 1);
Repeating background

Moving with the background

The background is moved by changing the offset of the texture attached to the material:
public class BackgroundMove : MonoBehaviour 
{
 public float speed = 1.2f;
 private Material material = null;
 private Vector2 offset;
 
 void Start () 
 {
  Renderer render = GetComponent();
  if ( render && render.material )
  {
   // Save the material reference and the texture offset value
   material = render.material;
   offset = material.mainTextureOffset;
  }
 }

 // Update is called once per frame
 void Update () 
 {
  // Move the offset ("Wrap mode" has to be set to "Repeat" on a sprite)
  if ( material )
  {
   offset.x += speed * Time.deltaTime;
   material.mainTextureOffset = offset;
  }
 }
}
Creating the illusion of parallax moving background is achieved by moving with further objects (background images) slower than closer objects (sorry for the low quality):

Wednesday, November 4, 2015

Yield bogeyman 1/2

When I first saw yield keyword in Unity I did not understand how it works. It looked like using yield keyword method could preserve its state between calls, which is something I was not able to find some parallel in C or C++. I started searching MSDN and other sites to find what the story behind this weird thing is. Below is what I found.

Let's start with the foreach loop. It could be used for looping over elements in classes, which implements IEnumerable interface (Let's save us now some time and let's not consider the generic IEnumerable<T> interface because I was using generics more than 10 years ago in C++ and to be honest I am not 100% sure how to use them correctly).

IEnumerable is an interface, which has only one method GetEnumerator() to be implemented. This method returns the IEnumerator interface. IEnumerator methods are then used to iterate through the collection. So if we want to create a custom collection, which could be used in forech loop, we have to implement both interfaces. This is the situation, where yield keyword will help us: As shown in the example below using yield removes the need for an explicit extra class IEnumerator when you implement the IEnumerable pattern for a custom collection. Example shows two implementations of the same task – one implementation uses IEnumerator, second uses the yield keyword:
Car class:
public class Car
{
 private string manufacturer;
 public string Manufacturer
 {
  get { return manufacturer; }
  set { manufacturer = value; }
 }
 
 private string model;
 public string Model
 {
  get { return model; }
  set { model = value; }
 }
 
 private int year;
 public int Year
 {                        
  get { return year; }
  set { if (year > 1900 ) year = value; }
 }
 
 public Car ( string manufacturer, string model, int year )
 {
  Manufacturer = manufacturer;
  Model = model;
  Year = year;
 }
}

Garage class with IEnumerator interface implementation:
class Garage : IEnumerable, IEnumerator
{
 private Car[] cars;
 private int index = -1;

 public Garage()
 {
  cars = new Car[5]{ 
   new Car( "Mercedes", "190E", 1991 ),
   new Car( "Fiat", "Uno", 1983 ),
   new Car( "Ford", "Escord", 1987 ),
   new Car( "Lada", "Samara", 1993 ),
   new Car( "Renault", "5", 1985 ) };
 }

 IEnumerator IEnumerable.GetEnumerator()
 {
  return this;
 }
 
 public bool MoveNext()
 {
  index++;
  return ( index < cars.Length);
 }
 
 public void Reset()
 {
  index = 0;
 }
 
 public object Current
 {
  get { return cars[index]; }
 }
}

Garage class with use of the yield keyword:
class GarageYield : IEnumerable
{
 private Car[] cars;

 public GarageYield()
 {
  cars = new Car[5]{ 
   new Car( "Mercedes", "190E", 1991 ),
   new Car( "Fiat", "Uno", 1983 ),
   new Car( "Ford", "Escord", 1987 ),
   new Car( "Lada", "Samara", 1993 ),
   new Car( "Renault", "5", 1985 ) };
 }
 
 IEnumerator IEnumerable.GetEnumerator()
 {
  foreach ( Car c in cars )
  {
   yield return c;
  }
 }
}

Loop:
void Awake () 
{

 Garage garage = new Garage();
 foreach ( Car c in garage )
 {
  Debug.Log( "[CAR]" + c.Manufacturer + " " + c.Model );
 }

 GarageYield garageYield = new GarageYield();
 foreach ( Car c in garageYield )
 {
  Debug.Log( "[CAR_YIELD]" + c.Manufacturer + " " + c.Model );
 }
}

Output:
[CAR]Fiat Uno
[CAR]Ford Escord
[CAR]Lada Samara
[CAR]Renault 5
[CAR_YIELD]Mercedes 190E
[CAR_YIELD]Fiat Uno
[CAR_YIELD]Ford Escord
[CAR_YIELD]Lada Samara
[CAR_YIELD]Renault 5
It works in a way that when a foreach loop is called and the yield return statement is reached, the current location in code is retained. Next time execution is restarted from that location. See one more example:
IEnumerable YieldTest()
{
 yield return 1;
 yield return 2;
 yield return 3;
}

void Awake () 
{
 foreach (int i in YieldTest())
 {
  Debug.Log( "[YIELD] Value: " + i );
 }
}

Output: 
[YIELD] Value: 1
[YIELD] Value: 2
[YIELD] Value: 3

Yield in Unity

Now, when we know how the yield works - how it is used in Unity?

In Unity method, which uses yield keyword is called coroutine - this I describe in the next part of the blog - after I understand it:)

Sunday, November 1, 2015

How I tried to understand the FixedUpdate() method...

Information below are not from my head - I have collected and copypasted them from several sources. The reason I put it on a single place was that I simply need to understand FixedUpdate() method on my own, which I am doing by coding, testing and blogging about it at the same time.

Unity documentation says that the FixedUpdate() method is called at regular interval, while Update() function is called as many times as possible, so we say it is called every frame, see there. Having a fixed interval is pretty useful, because of physics: E.g. if we add a force every Update() instead of FixedUpdate(), the game would run differently depending on the frame-rate.

Now, if you have call like the one below:
  void FixedUpdate ()
  {
    Debug.Log("FixedUpdate time :" + Time.deltaTime);
  }
You will notice in the console window that the deltaTime property, which returns in seconds time it took to complete the last frame, will return always the same fixed time. This is little misleading - Unity detects if the current call to Time.deltaTime is originated during FixedUpdate() call and returns Time.fixedDeltaTime value instead.

As mentioned here, calling something in regular intervals is not possible because of different devices performance. The solutions is that if FixedUpdate() hasn't been getting called often enough to average out to the correct interval between calls, it gets called multiple times (or isn't called if the frme rate is too high).

It is mentioned aslo in the Unity documentation: "FixedUpdate is often called more frequently than Update. It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at all if the frame rate is high."

In pseudo code I think the game loop is something like the one below. The physicsTime  is a virtual time, which si increased by adding physicsStep fixed value every time all FixedUpdate() method on all game objects are called. If we e.g. set the physicsStep to 0.02 and in the while loop is the difference between virtual time and real time (Time.time - physicsTime) is 0.07, because of e.g. low hardware performance during the scene rendering, the FixedUpdate() will be called 5 times in a row before next Update() call will be executed:
  while (1)
  {
     while ( physicsTime < Time.time )
     {
         CallOnAllGameObjectsFixedUpdate();
         physicsTime += physicsStep;

     }
 
     CallOnAllGameObjectsUpdate();
  }
In other words, first the appropriate number of physics steps are executed in order to "catch up" with the real time (and each step, FixedUpdate() is called on each object which implements it). Next, the graphics for the frame are rendered, followed by Update() on each object which implements it.

So, it is not true that FixedUpdate() is called in regular interval, but it is guaranteed that the same (almost) number of  FixedUpdate() calls will be executed every second.

See another nice explanation:
Let's set the physics timescale is 0.02, which this gives us 50 physics updates per second. If our game were running nice and fast at 100fps, we'd have two frame renders for every physics step - and therefore two calls to our Update() functions, for every call to our FixedUpdate() functions. (Key: "F" for FixedUpdate and "U" for Update)
0                                                0.1
|                                                 |
.____.____.____.____.____.____.____.____.____.____.___ 
F         F         F         F         F         F
U    U    U    U    U    U    U    U    U    U    U
If our game is running slower, say - at 30 frames per second (and therefore 30 calls to all Update() functions per second), it would mean that we actually sometimes have more than one physics step between each frame render. In the case of 30 fps, the result would be that sometimes two physics steps are executed between frames, and sometimes one, which would look something like this, for the first 10th of a second:
0                                                0.1
|                                                 |
.____.____.____.____.____.____.____.____.____.____.___ 

F         F         F         F         F         F
U                U               U                U
So, in most normal circumstances, you'll always get the desired number of physics steps per frame, and interleaved with these will be the visual frame updates, at as fast a rate as possible.

Tuesday, October 27, 2015

Game objects and components

Let's look on one of the most important concept in the Unity - game objects and components.

Everything we drag&drop (e.g. camera or sprite) on the game scene is called game object. On the C# script level the game object is an instance of the GameObject class (Note that GameObject class is sealed, so you cannot inherit from it). GameObject class does not do much on its own. It is rather a container for specialized classes, which are inherited from class of other type - Component.

For example: If I drag and drop the camera to the scene and I attach a script to it, you will see in the Unity editor something like this:


Camera in Unity editor UI
By dragging the camera to the scene I have created a new game object with several components in it. Let's now edit the script attached to the camera and let's put into its Awake() method following code:
Component[] components = GetComponents();
foreach (Component c in components)
{
   Debug.Log("Compontent: " + c.GetType() );
}
What happens there? The code in the script defines a new class inherited from Component base class. When the game is started the new object of the defined class is automatically instantiated and its instance is attached to the game object container like any other component.The Component class has a method GetComponents(), which returns list of all components of given type, which are attached to the game object to which the component (i.e. object from our script) is attached to. So in the case of camera the above code will create following list of class names prefixed with namespace. Note that the last item in the list is the script class itself:
UnityEngine.Transform
UnityEngine.Camera
UnityEngine.GUILayer
UnityEngine.FlareLayer
UnityEngine.AudioListener
RetroEngine.PixelPerfectCamera

Sunday, October 25, 2015

Samsung SmartTV?

Finding that Unity supports Samsung TVs was a little surprise for me. Unfortunately Samsung is the only supported brand and I did not find information about the planned support for other vendors' TVs and operating systems e.g. for LG's webOS or FireFox on Panasonic.

Smart TV in general is not really a game platform - TVs have performance problems and their remote controls usability is far from the standard game pad, so checking available games in SamsungApps and LG SmartWorld application stores I was not able to find anything that is worth to install and run. But it is not only Samsung and LG - comparing to others those brands are even doing pretty well because TVs from other vendors like SONY, Philips, Sharp, VESTEL, Toshiba, Panasonic, Grundig, etc. are ignoring games almost totally and they focus mostly on entertainment video and audio applications. Might be new Apple TV and android TV will bring some change there.

Working in the video streaming industry I have access to many Samsung Orsay (2012-2014 models) and Samsung Tizen TVs (2015), so I decided to launch a small demo to see how it works.

The important is that not every TV from Samsung is compatible with Unity. See the list of supported devices:


On the other side I was able to install and run a demo application on every 2013+ TV model I found (including cheap low-end 2013 5xxx TV series). To launch the application in the debug mode, the Unity Launcher application needs to be installed and started on TV first. Unity Launcher is available in the SamsungApps application store:

Samsung Tizen Unity Launcher 
Samsung smartTV Orsay (2013)  Unity Launcher
Samsung smartTV Orsay (2014)  Unity Launche
To upload the application the FAT32 flash drive with sufficient space for game upload must be inserted into TV's USB slot. Once the Unity Launcher is started on TV it exposes the web http interface (using port 8899) for application upload, launch and for accessing debug logs from the Unity framework combined with Debug.Log() output from the application.

Unity Launcher web interface
In general my short test on few devices shows that using Unity it should not be a problem preparing a simple game for Samsung TVs. I did not face a single problem - everything during my test worked as expected, which is not really common situation in TV world:)