Tag Archives: Unity

Am I really ready to Graduate?

I don’t think my aims have changed since starting this course.  I wanted to marry my animation skills with programming and either create my own games/apps or use these skills to get me further into a late career in the industry.

C++ nearly broke me and perhaps that is a sign of being too old to adapt between different languages.  What the last two studio subjects have taught me is that I want to be a Unity developer when I graduate.

It seems, from reading the job market correctly, that the main concerns left for me are to gain an understanding of the Mechanim system, Animation trees and experience with a range of repository formats (my only experience to date has been Git).

http://positron.applytojob.com/apply/212a0d256b69767c530055704667635e4c4414022e002f1302056a0e3e08277f130003/Game-Developer?source=INDE&sid=KEozYYGIc4eCtVVgxrKPo1nXTM9XlXe5CDF

https://au.jora.com/job/Unity-Developer-d4c05512962c672f7af8241b8ce5609f?from_url=https%3A%2F%2Fau.jora.com%2FUNity-3D-Developer-jobs&sp=serp&sponsored=false&sr=1

http://www.tsumea.com/news/230715/experienced-unity-developer

http://www.tsumea.com/news/020715/unity-prototype-designer

http://forum.unity3d.com/threads/paying-job-developer-animator-to-work-on-puzzle-platformer.326355/

Next Trimester, I am working on the Final Project, which meant that I will be looking at Animation Trees over the holidays and implementing a few of my previous animations so that I can readily understand how they work and how to best leverage them.  This way I will be prepared to implement animations as soon as we return from the holiday break.

Also, next trimester, I will be working with a group of ex-qantm students who have their own studio and are trying to get their game “Hands Off” greenlit through Steam.  I will be doing rapid prototyping for them for new game ideas and improvements or new concepts for the “Hands Off” title.  They will expect me to be knowledgeable in using Bitbucket and TortiseHg, which I will also be looking into over the holiday break.  As I am already conversant with using Git, I’m sure that it will not be a culture shock using Bitbucket and TortiseHg.

I think it will be a very busy lead up till the end of the year, but I am looking forward to it.  Perhaps because I am finished with C++, but I can’t just leave it there.  Some of the advertisers looking for Unity developers also recommend Unreal experience.  While I have used Unreal to show off Modeling assets and have used the Kismet system, I doubt that this would be enough to warrant a job so I will need to continue with my C++ training and try to become a lot more proficient in it.  Who knows, I might even begin to like it.

For something completely different.

For a recent side project in Unity, I was trying to find out if certain game objects were seen by the main camera.

To sum up what I was trying to do, I wanted to have enemies able to be highlighted (using a basic outline shader) if they were on screen with the player.  This meant finding if they were on screen with the player, collecting their game objects into a list and cycling through that list to change which enemy is the current target for an attack.

My initial research led me to OnBecameVisible() and it’s opposite, OnBecameInvisible().  This is supposed to tell the renderer when the object comes on screen, or any part of it, including it’s shadow, and needs to be rendered.  What sounded good on paper failed to work in reality.  One drawback is that it is hard to test in the Unity editor because the editor camera also affects the outcome (allegedly).  I say allegedly because I could not get it to work regardless.

What I ended up relying on were two GeometryUnity functions.  CalculateFrustrumPlanes and TestPlanesAABB.

On the script for the object I wanted to test, I used these variables:

private Plane[] planes;
public Camera cam;
private Collider coll;

The main camera is dragged onto the Camera slot in the inspector, although, with a prefab, it might need to be coded directly into the Start() function, where I used this piece of code to access the collider.

coll = GetComponent<Collider>();

In Update(), because the camera is moving with the player, I needed to constantly tell the script what is planes[] were using:

planes = GeometryUtility.CalculateFrustumPlanes(cam);

The script would then announce that it was visible by referring to an external bool function:

if(IsVisible()) {..//insert mad code here//..}

This was a very simple function that returned true when the collider could be “seen” by the main camera and false when it couldn’t.

bool IsVisible()
{
return GeometryUtility.TestPlanesAABB(planes,coll.bounds);
}

This code was used for a prototype to prove that I could implement this mechanic, although after implementing it, I realised that it was rather boring for the purpose I had envisaged and will likely be scrapped.  One of the rules of Game Design is that you have to be prepared to “kill” your children.  As a father, I find this is a horrible metaphor, but true still the same.

My main concern with this current layout was if, in the long run, the amount of processing and garbage generated would have been worth knowing what was visible.  In my thinking, it couldn’t be worse than having a raycast every frame to tell if the player is grounded, or not.

I am posting this in case I have to revisit the concept in the future (3 strokes plays havoc with the short term memory) and if anyone else needs to know a working way to detect if something is currently on screen.

Unity 5 and the recording of pulse rate with the Arduino.

One of my tasks this Trimester is to get feedback and use it, from something other than standard game controllers or the mouse.

I have teamed up with designer, Savik Fraguela (yet again), and I am providing bio-feedback for his game.  In order to keep it inexpensive at this stage, I am using feedback obtained from an Arduino board and software that comes with the “Pulse Sensor” from http://www.pulsesensor.com.

This meant that I needed to download and install several Software suites and the FDTI drivers.  The drivers were a pain in my case because I am using Windows 8 and this operating system hates using unverified, or unsigned drivers.  I had to get past that by following the directions on this site : https://learn.sparkfun.com/tutorials/disabling-driver-signature-on-windows-8

Installing the rest of the software was uneventful as was attaching the monitor to the Arduino board.

I was able to get the software (called a sketch in Arduino Studio) running and pushed onto the board.  I was also able to get the serial driver showing what feedback was comint through the port.

My first problem came when trying to write my Unity script.  I eventually had errors saying that the serial was not open.  By this stage, I had to return the Arduino hardware to my Lecturer, but I suspected that it was because ArduinoStudio was using the port to read the information.

This was confirmed over the weekend.  I again ran Arduino Studio but didn’t display the Serial Port in that suite.  Unity had no problems with the set up.

Now the fun part.  I am used to manipulating gameobjects, and not so much strings and byte[] and char[].

I was trying to put the data from the serial port into a char array and specifying the length as 5, because the data being sent was a Letter that indicated what sort of information was being sent, then an int of 2 or 3 characters and then a carriage return.  I was able to display only the numbers and nothing else.  The code I was using was serialPort.ReadByte().

I eventually found (thanks Google) that I should be reading using serialPort.ReadLine() and copying that to a string.  This allowed me to read the whole line of data coming over the serial port in the format of S203, etc.

The incoming data was split into three categories.  Data that starts with an S prefix which gives the user raw data.  Data with a Q prefix that is apparently some sort of time measurement from the last beat and data that has a B prefix, which is the one I wanted as it is the beats per minute.  This is taken over 10 beats and averaged out for a minute.

c# strings are so easy to work with.  I thought that I would have to split the string down into a char array and try to work with that, but as it turns out, a string is already a char array.  Each element can be dealt with as string[0], string[1], etc.  That was fine until I tried to use this to find out the start of the string .. if(string[0] == “B”).  I was told that Unity couldn’t compare a string with a char.

More searching and I found that you could do this if(string.StartsWith(“B”)).  This has me beat.  It sounds the same as if(string[0] == “B”), but Unity accepted that and it worked.  I was now getting all of the data that had the B prefix.  I did notice that the information seemed to be fluctuating pretty steadily, and occasionally wildly.

Because there was no guarantee as to how long the ints were, they could be 2, 3, or 4 numbers long(although in the case of the B prefix, it is fair to assume that they will be only 2 or 3 numbers long) I made use of string.Length, they are arrays after all.

As only the B data is coming through to this point, I then created a new temp string and appended it with the contents of my original string, excluding the prefix.  I then converted that temp string into an int.

In order to try and settle down the fluctuations, I created a List of ints and when the count reached 5, it would take the average of those bpm and return this new bpm. (after removing the first member of the List)

I know that Savik will be using an enum to gauge the factor of how scared the player is and using that enum to ramp up the fear inducing elements of his game.  If this list isn’t stable enough, I will look at making the list longer and even consider taking the highest and lowest values out, then averaging the rest and using that information for the new bpm.

In conjunction with this, we were considering using OpenCV and OpenCVSharp (and even some other formats) to use facial tracking from a web cam and supplement information from them to aid in the bpm.  I will write another blog about this regardless of whether I can get it working in Unity 5, so that someone can see the effort I have put into trying to get it working and perhaps show me if and where I went wrong.  I did find a project that will work in Unity 4, but there seems to be a problem with Unity 5 reading the haars_Cascade_facial .xml file.

In the mean time, here is the file that I used to get the pulse monitor working with in Unity:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.IO;

public class SerialListener : MonoBehaviour
{
public SerialPort serial = new SerialPort(“COM3”, 115200);//create new serial port
private string beat = “”;// string to hols the data in
private List<int> beatPM = new List<int>(); //List to hold the beats

void Start ()
{
//open a new connection
OpenConnection();
}

void Update ()
{
beat = “”;
//Read data input … should be a letter to start (char)
//then 3 numbers and then carriage return
beat = serial.ReadLine();
//        print (beat);
//Create an int that can be used by the Client
int somethingToSend = AnalyseBeats(beat);
print (somethingToSend);

}

void OnApplicationQuit()
{
serial.Close();
}

//Function connecting to Arduino
public void OpenConnection()
{

if (serial != null)
{
if (serial.IsOpen)
{
serial.Close();
print(“Closing port, because it was already open!”);
//message = “Closing port, because it was already open!”;
}
else
{
serial.Open();  // opens the connection
serial.ReadTimeout = 1000;  // sets the timeout value before reporting error
print(“Port Opened!”);
//        message = “Port Opened!”;
}
}
else
{
if (serial.IsOpen)
{
print(“Port is already open”);

}
else
{
print(“Port == null”);
}
}
}
int AnalyseBeats(string str)
{
//Data comes in with a “S” header, a “Q” header or a “B” header
//S = raw data .. “Q” is (allegedly) the time since the last beat was detected
//and B is the one that we want.  It is the beats per minute averaged over 10 beats

if (str.StartsWith(“B”))
{
//            print (“Original data.” + str);
//create a new string
string t = null;
//append to t everything except the starting letter
for(int j = 1; j<str.Length; ++j)
{
t += str[j];
}
//Convert that string into an int
int temp = int.Parse(t);
//            print (“Modified data.” + temp);
//add that int to the list
beatPM.Add(temp);

}
//        print (“BMP.count.” + beatPM.Count);

//Create an average of the BPM to give a more stable reading of the current pulse rate
if(beatPM.Count >=5)
{
int bAv = 0;
for (int i = 0; i < beatPM.Count; ++i)
{
bAv += beatPM[i];
}
bAv= (int) bAv/beatPM.Count;
//            Debug.Log(“Average over last 5 beats = ” + bAv);
beatPM.RemoveAt(0);
return bAv;
}

return 0;

}
}

My struggle with a Check Point Manager

My current project needed a manager to record where the players need to respawn in the event of their death.

While it was unlikely that they could actually die in the Tutorial area of the game, I made sure that they would still respawn at the start of the level. When it came to the players going though a trigger to change the spawn point, I found that just using the following script, wouldn’t work.

using UnityEngine;
using System.Collections;

public class DontDestroyMe : MonoBehaviour {

// Use this for initialization
void Start () {
DontDestroyOnLoad (gameObject);
}

// Update is called once per frame
void Update () {

}
}

While this instance doesn’t destroy itself, it actually creates another instance of the CheckPointManager which seems to take priority over the current instance of the script and returns null object exceptions when trying to find the individual check points.

My research on the internet eventually led me to this site : http://unitypatterns.com/singletons/

This led me to using this for my CheckPointManager:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CheckPointManager : MonoBehaviour
{
private static CheckPointManager _inst;

public static CheckPointManager inst
{
get
{
if(_inst == null)
{
_inst = GameObject.FindObjectOfType<CheckPointManager>();
//Don’t destroy
DontDestroyOnLoad(_inst.gameObject);
}
return _inst;
}

}

public List<GameObject> checkPoints = new List<GameObject>();
public GameObject atlCharacter;
public GameObject ollinCharacter;

public bool spawnPoints = true;
public bool firstCheckpoints = false;
public bool secondCheckpoints = false;

void Awake()
{
if(_inst == null)
{
//If I am the first instance, make me the Singleton
_inst = this;
DontDestroyOnLoad(this);
}
else
{
//If a Singleton already exists and you find
//another reference in scene, destroy it!
if(this != _inst)
DestroyImmediate(this.gameObject);
}
}

 

Through testing, I found that when the game returned to the menu, the CheckPointManager was still operating and throwing Null object reference exceptions.  I modified the awake function to the following:

 

void Awake()
{
if(_inst == null)
{
//If I am the first instance, make me the Singleton
_inst = this;
if(Application.loadedLevel == 0)
DestroyImmediate(this.gameObject);
else
DontDestroyOnLoad(this);
}
else
{
//If a Singleton already exists and you find
//another reference in scene, destroy it!
if(this != _inst)
DestroyImmediate(this.gameObject);
}
}

The next problem was with the actual checkpoints.  as they were being destroyed, I ended up using the first “DontDestroyMe” script on the empty game object that was the parent of the individual check points.

This ended up working perfectly, for this project, at least, but I think it should work on any future game.

 

Particles …

We had been operating on the assumption that many particles would slow down the frame rate, so just to make sure, I created a particle system to replicate the fog and tried it out.  I was able to create 60 000 particle fog with no real detriment to the frame rate.

Base frame rate for the scene .. range between 73 and 93 fps.

Base frame rate for the scene .. range between 73 and 93 fps.

Particle system running 60 000 particles with frame rate ranging between 80 and 93 fps.

Particle system running 60 000 particles with frame rate ranging between 80 and 93 fps.

I was hoping that there would be more editable factors from script, in the Shuriken Particle System in Unity, but that was not the case.  There is very little that can be edited from a script.  I was hoping that I would be able to control the size of the emitter by changing the radius of the circle.  This would allow for the slow decreasing of the fog in toward the player’s position.

While scrolling through the “Shape” option, I came across using a mesh for the emitter.  I created a circular mesh that was deformed, but when applied, I still couldn’t make any changes to the mesh as it was now embedded into the particle system.

What I did then was to attach the component for the Particle System and replicate the settings.  This gave me the opportunity to slowly rotate the particle effects so that it wasn’t a constant visual image and to also decrease the local scaling of the emitter so that it closed in on the players.

Particles emitting from a mesh and slowly revolving and scaling in towards the player

Particles emitting from a mesh and slowly revolving and scaling in towards the player

This is my first time using the Shuriken system however I have used the Legacy Particles in previous projects.  I set the duration of the clip for 30 seconds so that it wouldn’t appear so regular and having regular patterns seen by the players.  It is also set to looping because once it is on, it is going to stay on.  For the purposes of setting the particle system up, I also used pre-warm, but I am seriously considering using that setting when applying it in our game because it looks like crap when is starts off.

 

The start speed is set very low at 0,02 because it is a slow moving fog.  The start lifetime is set at 10 and this gives the height of the effect.  I have also set a large particle size because I want it to be seen from a distance and I wanted to block out as much of the background as I could.

To try and make the fog rolling, I set the initial rotation and it is rotating all the way through the particles life.\

There is a slight negative gravity so that the particles slowly rise into the air and they inherit 50% of the rotating velocity from the mesh.

I have also set the size of the particles to quickly fall to zero near the end of their life.  I believe that this also helps to give the impression of the fog rolling and seeming to rise up and roll over into the background.

This is by no means finished as far as the final fog will go but it is certainly enough for proof of concept and will suffice until the polish stage of the project.

The other thing I am considering is I am currently using a vertical ring shaped mesh and I would like to change it to a thin horizontal ring shaped mesh.  This will give me greater control to manipulate the mesh through script and try to follow the contours of the terrain when it has been modeled.