Smooth Blinking Function

This is something very useful that I have implemented many times.  Using the power of trigonometry you can get a cool blinking effect.

Here is the basis of the function:


Math.Cos(<float>) will return a number between 1 and -1. It also has a nice curve to it, so the closer you get to 1 or -1 the slower the value with change. Using Time.timeSinceLevelLoad in Unity for the TIME variable will return a value that is bouncing back and forth between 1 and -1.

We can use the SPEED variable to speed up or low down how fast the value changes.  Since without the SPEED variable it would take 3.14 second for the value to change from 1 to -1.  So having a large value in speed will increase how quickly the value changes.

The RANGE variable can modify the value that you are bouncing back in forth between.  This works together with the OFFSET variable.  For example if you were modifying a color normally you wouldn’t want to go into a negative number.  Knowing that the Mathf.Cos() function is always could to return a value between 1 and -1 you can do some simple math to work out what the RANGE and OFFSET should be to make the value useful.  For example if you set RANGE to 0.5 and OFFSET to 0.5 your final value would be between 1 and 0.  As a RANGE of 0.5 would modify the Mathf.Cos() value to between 0.5 and -0.5.  They you add the OFFSET of 0.5 and your get your final values moving back wand forth between 1 and 0.

Here is an example where I am modifying the alpha color of my sprite so it blinks and the blink speeds up as time goes by:

 float lifeTime = 0;
 float timeMax = 8;
 float blinkStart = 4;
 void Blink()
        lifeTime += Time.deltaTime;
        if(lifeTime > blinkStart)
            Color c = spriteRender.color;
            c.a = Mathf.Cos((lifeTime – blinkStart) * lifeTime) * 0.4f + 0.6f;
            spriteRender.color = c;
        if (lifeTime > timeMax)
As you can see the lifeTime variable is modifying the speed of the blink and the value for lifetime is increasing as time goes by.  I am also using the blinkStart to make sure starting value passed into the Mathf.Cos() function is 0, as that will return a 1.  That is to prevent the color jump to another value which would be jarring.

Calling Unity Function from XAML and Using Microsoft Advertising

I had been struggling for a while to get Microsoft Advertising working in my latest Unity game that is being published on the Windows Store.  I played around with trying to add the library into Unity as an asset and use compiler directives in my Unity scripts.  That worked the first time I tried it, but then it it stopped working with no real changes and it was throwing some weird run time error.  I thought there has to be an easier way… and there was!

The method I ended up using was, invoking a Unity functions from XAML.  This was so much simpler for me.  Within the MainPage.xaml.cs I was able to add some code so I could access the Microsoft Advertising Class (Microsoft.Advertising.WinRT.UI) from my Unity code via a delegate.  Just the ability to be able to call Unity functions from XAML and XAML functions from Unity can be very useful!

Here are the steps I took to get video ads working in my game.

Create an empty game object called “MS_Ad_Controller” and create a new Unity Script on that object that looks like the following:

public class AdController: MonoBehaviour
public delegate void OnEvent();
public OnEvent showVideoAdEvent = null;

public void ShowAd()
if (showVideoAdEvent != null)


This script defines a delegate that takes no arguments call OnEvent, creates an instance of that delegate called showVideoAdEvent, and a function called ShowAd that executes the delegate if it has been set.  We will assign this delegate later in from the XAML code.

Now you have build your project for Windows Store WS_Build_SettingsOnce the project has been built open it up in Visual Studio.  For the video ads you will need to add a reference to Microsoft Advertising Universal SDK (adding this will also add Microsoft Advertising SDK for XAML).

MS Ad Ref

In the XAML project open up MainPage.xaml.cs and add the following “using” statement so we can reference the video add functionality:

using Microsoft.Advertising.WinRT.UI;

Now at the end of the MainPage constructor we need to add a line to setup our delegate after the Unity Player is running and the Unity objects have been created.  We that through and EventHandler.

UnityPlayer.AppCallbacks.Instance.Initialized += OnInitialized;

Now create the OnInitialized function that is being reference in the above line using this code:

private void OnInitialized()
AppCallbacks.Instance.InvokeOnAppThread(() =>
UnityEngine.GameObject go = UnityEngine.GameObject.Find(“MS_Ad_Controller”);
if (go != null)
go.GetComponent<AdController>().showVideoAdEvent = new AdController.OnEvent(XamlShowAd);
throw new Exception(“Controller not found!”);

}, false);

Using AppCallbacks.Instance we are invoking code on the app thread.  The app thread is where the Unity code is running under the UnityPlayer.  First we are finding our GameObject called MS_Ad_Controller that we created above and then setting the delegate in the AdController Unity Script that was attached to it.  We have to create the XamlShowAd function that is being set in the delegate and the event handlers for it.

private void XamlShowAd()
Debug.WriteLine(“Starting FetchVideoAd()”);
// Define ApplicationId and AdUnitId.
// Test values are shown here. Replace the test values with live values before submitting the app to the store.
var MyAppId = “d25517cb-12d4-4699-8bdc-52040c712cab”;
var MyAdUnitId = “11389925”;

MyVideoAd.AdReady += MyVideoAd_AdReady;
MyVideoAd.ErrorOccurred += MyVideoAd_ErrorOccurred;
MyVideoAd.Completed += MyVideoAd_Completed;
MyVideoAd.Cancelled += MyVideoAd_Cancelled;

MyVideoAd.RequestAd(AdType.Video, MyAppId, MyAdUnitId);


void MyVideoAd_AdReady(object sender, object e)
if ((InterstitialAdState.Ready) == (MyVideoAd.State))
UnityPlayer.AppCallbacks.Instance.InvokeOnUIThread(new UnityPlayer.AppCallbackItem(() =>
), false);


void MyVideoAd_ErrorOccurred(object sender, AdErrorEventArgs e)




void MyVideoAd_Completed(object sender, object e)



void MyVideoAd_Cancelled(object sender, object e)


In the code above we are requesting an ad, then when the ad is available we are playing.  You might want to change the flow here to suit your game.  Specifically fetching the ad ahead of time and having it waiting.  If you use the above code there will be a few second delay before the ad starts.

Now all you need to do is hook that ShowAd function in the AdController class up to a button of something to be able to display a video add.  The ad will be full screen and obscure your game, but your game will keep running, so that is something else to think of.  Using the event handler and invoking code back and forth you should be able to setup a decent flow.

Oh yeah, as the comments in the XamlShowAd function state you need to replace the ID’s with your own or you will not get paid!  You create those in the Windows Developer Dashboard under the specific game by selecting “Monetization” from the left hand menu.

Whew, that was a long post, but I hope this helps someone.  I found the documentation around all this to be pretty light.

Windows Universal App and Unity3D WWW Caching Fun!!!!

In working on my latest game I am using the Unity WWW class to fetch some information my webserver.  No problem the code is easy:

public IEnumerator Get()
data = “”;
WWW www = new WWW (URL + “getRandomObject.php?”);

  yield return www;

if (!string.IsNullOrEmpty(www.error))
data = “Error: ” + www.error;
data = www.text;
Debug.Log(“Get result: ” + data);

  www.Dispose ();
My head tester (thanks Dad!) found a bug where the game was getting in stuck in an infinite loop.  I tested in and could not duplicate, I opened up the downloaded Windows Store version and sure enough I could duplicate the issue.  Back to the Editor and nothing… So I built a development build including the “Unity C# Projects” and proceeded to duplicate the issue.  Now the “getRandomObject.php” script should return a different result each time or have very low odds of returning the same object.  As I ran the Windows Universal App from Visual Studio I saw I was always getting the same return value as the first time I requested it!
BAMN, caching!  Not happening in the Unity Editor, but it is happing in the WUA.  Luckily the fix was simple.  Just make the URL you are fetching different each time:
WWW www = new WWW (URL + “getRandomObject.php?t=” + UnityEngine.Random.Range(0, 10000).ToString());
Appending the “?t=<some random number>” doesn’t affect my get, but it should prevent caching from being an issue.

Windows Store App Icons and Inkscape

While working on a Windows 10 Store game in Unity I noticed the requirements for a ton different icon resolutions.  I created my icon in Inkscape and exported one manually before I thought, “hey, can I batch this somehow?”.


Sure enough I could!  Inkscape has some nice command line options.  I created a little batch file to save out all the resolutions I needed.  Here is the command:

c:\Program Files\Inkscape\inkscape.exe “icon.svg” –export-png=”icon-30×30.png” -w30 -h30

To do this create a file called “Create Icons.bat” copy and paste the above command in and copy it multiple times updating the Inkscape file name, export file name and the “-w” for width and “-h” for height.


Double click file and all your icons are created!  Great for quickly seeing what they look like at all resolutions and then making changes.




Importing Git Repository into Android Studio

I am a bit new to Git and GitHub and I was having some major issues trying to clone a Git repository and then open it up with Android Studio.  I searched and searched, but did not find any clear instructions on how to do it.  When I selected the “Check out project from Version Control” on the “Welcome to Android Studio” screen I was able to successfully clone the remote project to my computer, but when I attempted to open it I receive error messages about missing “IML” files for the modules and project was completely empty.  After a bunch of trial and error I found a really easy way to clone the remote repository.

Android Studio 1

First select “Check out project from Version Control” and you will be presented with the following dialog box.  Enter URL of your Git repository. The next two field are where you want the project imported to on your computer.

Clone Rep

After the clone is completed you will be asked if you want to open the project.  Select “No” to this.  Next Select “Import project (Eclipse ADT, Grade, etc,)” from the Welcome screen.  Then select the directory where you cloned the project to on your computer.  The project should build and generate all the files you need.  That is it!

See the problem is by default the “Gitignore” file has a “.iml” entry the app and module “.iml” files will not be included in the versioning.  These files are needs by Android Studio to see how the project and modules are laid out, but they do not affect the build of the app.



Unity Saving/Load Game Data

Previously when saving and loading of game data I was using the Binary Formatter.  This would the serialized data in binary format instead of plain text to prevent easy save file manipulation.

However, when I went to build my game for the Windows Store I found out that that class is not available.  I liked the flexibility of serialization of a class for my save data, but I did not want to have it stored in plain text XML which would be very easy to understand and edit as it would look something like this:

<?xml version=”1.0″ encoding=”Windows-1252″?>
<PlayerData xmlns:xsi=”” xmlns:xsd=””>

You wouldn’t need to be an L33T haxor to figure out how to bump your score up if that was the contents of the file.  I played around the built in encryption classes in .NET with some success, but that seemed like overkill to use full 128 bit encryption.  Instead I wrote my own simple encryption algorithm:

string saveFile = Application.persistentDataPath + “/gameInfo.dat”;
MemoryStream stream = new MemoryStream()
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
serializer.Serialize(stream, playerData);
byte key = 47;
Byte[] array = stream.ToArray();
for (int i = 0; i < array.Length; i++)
     array[i] = array[i] ^ ((byte)(i % key));
MemoryStream stream2 = new MemoryStream(array);
stream2.WriteTo(File.Open(saveFile, FileMode.Create));

This will take the memory stream from the serialized data and XOR each byte with it’s own index modulus a key.  The key can be anything number between 1 and 254 to make is secure.  To decrypt the data do the same:

FileStream stream = File.Open(fileName, FileMode.Open)
byte[] fileBytes= new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
for (int i = 0; i < fileBytes.Length; i++)
    fileBytes[i] = (byte) (fileBytes[i] ^ ((byte)(i % 100)));
MemoryStream stream2 = new MemoryStream(fileBytes);
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
playerData = (PlayerData)serializer.Deserialize(stream2);

The data in the save file will look something like this:

>znh%pbzzcdb0,>>!03q{ux|pt|!?IvNEMTW $`]SJQGrVLXCQQPLz91*yg.3<9pdc:98~&a};’1xjijjs3

If there was sensitive data (personal, password or billing information) going to be stored in the file at that point you should definitely spring for a full strength encryption method, but this will do for local save game data.

Unity 5 – 2D Player Sprite Animation Setup

I was playing around today with a setting up a good solution for a three-quarter view of an animated player.  This is what I came up with:


The default state is the idle down. All the walking animation can transition from “Any State” and each of the walking states can only transition to their related idle states.

To make the transitions I am only using a single “Int” parameter called “WalkDir” that has a default setting of 0.

Each of the transitions from “Any State” to a walking is setup to use a value of “WalkDir” from 1 to 4.  So the transition from “Any State” to “Anim_PlayerRight” is when “WalkDir” is equal to 1, “Any State” to “Anim_PlayerDown” is when “WalkDir” is equal to 2, “Any State” to “Anim_PlayerLeft” is when “WalkDir” is equal to 3 and “Any State” to “Anim_PlayerUp” is when “WalkDir” is equal to 4.

Next each of the transitions from the walking states to the idle states is set when “WalkDir” is equal to 0.  This makes it so we will only transition to the correct idle state.

This is makes a nice and simple animation controller only one parameter needs to be set.  It could be easily be expanded to include diagonal movements, making a total of eight directions.

PS: When I was setting this up I had some difficulty. I was creating my sprite animation by dragging multiple sprites into the “Hierarchy” view, but then I could not figure out now to edit them.  I kept trying to select the animation clip (*.anim) file itself by selecting it from the animator or under project, but nothing would show up in the “Animation” tab. Then after googling for a while and not finding a solution I figured out you need to select the game object in the “Hierarchy” view that has the “Animator” component attached.  Then you can select the animation clips in the “Animator” tab and can edit them.


Unity – Windowed Interface for 2D

Recently I have decided to make the switch to Unity from XNA.  The first project I am working on is a PC version of Dungeons of Desolation.  One of the challenges with porting an Xbox game to PC is the changes to the controls and interface.

The new user interface is going to be all windows.  The windows can be opened/closed and dragged around by their title bar as people are already familiar with this from the Windows operating system.  Multiple windows can be overlapping and mousing over a window will make it active.

To implement this I created an empty game object that is a child of the main camera and add all the graphic items as children. The child objects include a background, border, tile bar with the window name and a close button.  The parent game object has BoxCollider2D that is set to the size of the window.  This is used for determining if the mouse if over the window so the we do not pass the input to the normal game play.  The parent object has a script assigned to it that inherits from a “Window” class that itself is a child of the “MonoBehaviour” class.

Here is the code that is used to check if a window is active:

bool CheckWindowActive(Window window, Vector3 mousePoint)
return window.gameObject.activeSelf &&
(window.windowCollider.OverlapPoint(mousePoint)  &&
!(activeWindow != null && activeWindow != window &&
activeWindow.gameObject.activeSelf &&
activeWindow.windowCollider.OverlapPoint(mousePoint)))  ||
window.draggingItem ||

  • The check for “activeSelf” is to see if the window is visible.
  • The “OverlapPoint” check is to see if the mouse over the window.
  • The “activeWindow” checks are to see if there is another window that is above the current one that the mouse is over too.
  • The “draggingItem” checks to see if the player has dragged an item out of the window and if they did the window should still be considered active.
  • The “movingWindow” checks to see if the player is dragging the window by the title bar as the mouse might leave the window as they are doing this.

The child objects of the title bar and close buttons have there own BoxCollider2D that are used to check if the mouse if over them so they can be activated.

This can be seen in action in a Web Player Development build I have posted:

To open the windows press:

  • P – Player Info
  • I – Inventory
  • M – Map

XNA PC GUI – Buttons and Scroll Bars

Working on a PC version of Storage Warfare.

It needed some new controls for PC input to replace the Xbox controls.  I decided to take my time and create some reusable classes.  Click the click of the control to download the code for it.

Button: Created a button class that can be used in an IF statement and/or trigger an event when pressed.  A standard image can be used or a new one passed as an argument.  The image I used to the button looks 3D with darker shading on the bottom so when the button is pressed I flip it making it look depressed. Also, it is slightly darker when the mouse isn’t hovering over it.

Button Handler:  A class to managing the updating and drawing of a many event driven buttons.

Scroll Bar:  A scroll bar that will just pass back an the current start of a list.  It will scroll using clicks/drags on the bar itself or using the mouse wheel.

Next up: radio buttons, text fields, numerical fields and how I did the global leader-board!

XNA Pathfinding continued…

I thought I would expand on the pathfinding sample I posted last.   I know from personal experience having path developed is only the first step.  Getting an NPC to travel that path was more diffcult to implement than I thought it would be when I first was working on my first game.

Here is an updated pathfinding sample that contains an class called “Agent” which could be a computer controlled enemy or NPC in a game.  This class uses the same A* class from the last sample to travel back and forth between the start and end nodes.

XNA 4.0 A* Sample 2 Download

It might be a bit confusing why I have two different locations in the “Agent” class.  One location the agent’s location within the tile grid called “tileLocation” and the other is the onscreen co-ordinates called “drawLocation”.  The “tileLocation” variable is used to update the “tileInfo” which is out level layout that holds all the pathfinding information.  Even if you are not making a tile based game you still are going to use a similar method to layout your pathfinding data.  The “drawLocation” variable is used to determine where to draw the agent on the screen.

This is just a basic sample real time pathfinding to a moving target is much more complicated.  Especially when you have mutliple agents involved that could block each others paths.