Sunday, July 20, 2014

Art director assigned

So we have an announcement to make. I have officially employed an art director for my new game. One of the perks of being married to a brilliant artist. We sat down last night and fleshed out a few design details.

We picked a tentative working title of Space Invaders 2.0. There are probably a thousand different reasons we won't be able to use that in the final game, but it works for now. Can't really keep calling it the 'new game' forever.

The story starts soon after the time of classic space invaders. The aliens get together on the mother ship and finally agree that the strategy of going side to side is just not working any more. The humans are able to predict every movement. Various strategies are discussed, moving up and down, diagonals, and sine waves are all discarded. 

Then one alien suggests giving the pilots the ability to change tactics depending on the human tactics. A hush descends over the mothership as the idea sets in. The first few waves are a disaster, but the alien's prove to be fast learners, quickly discovering how to dodge bullets, and how to concentrate firepower for maximum effect.

On the human side it's going to be a classic upgrade game. Play a few levels, earn some cash, buy some bigger and better weapons, repeat. Game play will involve defending this skylines if iconic cities around the world. And maybe a few sheep on the secret level.

And as a final tribute to the original the game will start with a single level of classic play, a tutorial of sorts. Will probably throw some sort of endless play mode in after the campaign too.

Let me know in the comments if there is anything else you'd like to see.

Tuesday, July 15, 2014

The awesome power of coroutines

When I first started learning Unity I saw was introduced to the concept of a coroutine. Coroutine a seemed like a nifty way to cause something to happen later in your script. I scoffed at the idea and built myself custom timers.

There were a couple of reasons I chose not to use coroutines. The first was the complexity. It's far easier to understand what code is doing when you can see everything yourself. The second was a misunderstanding of how coroutines worked. I made the assumption that my code would be just as efficient. After all, how much simpler can you get then updating one float each frame?

So I was doing some research for a question on Unity Answers, when I stumbled across how awesome coroutines actually are.

Coroutines are more efficient then manual timers. This is because Unity handles all of the coroutines on a single event system, with one timer. So where I had one to increment one float per method, Unity has one float that manages all of the coroutines. 

Coroutines also help coding simplicity. No need to check against a timer in you Update loop. In fact well structured coroutines can be set up with a single line of code. In some cases you can eliminate the need for an Update function altogether.

Perhaps the coolest thing about coroutines is they stop running once they are finished. This sounds kind of obvious, but it represents a huge efficiency gain over Update. Take a movement script as an example. The traditional way to code this is to set a bool isMoving. The bool is checked each frame in Update. Each time the bool returns true the movement code executes. Once the target is reached the bool changes to false. However the bool is still checked every frame. Not particularly expensive, true. But do it multiple times on multiple game objects, then run it on an and old mobile phone, and it will all add up.

Contrast this to a coroutine. Once the movement starts there is still an internal check every frame. However as soon as movement finishes, no more overhead. This gets even better when you apply it to a function that gets doesn't execute every frame. 

So that's today's revelation. Still waiting on the computer to get back from the shop, so no progress on any actual games yet...

Saturday, July 12, 2014

From the phone.

So turns out the problem with Megan's computer was a faulty hard drive. We have yet to hear if any of the data can be recovered. And like a genius I didn't back up any of my games. So you won't be seeing any improvements on the tower defense game anytime soon. 

The good news is this frees me up to work on a new project. This one is going to be a remake of space invaders. A good old fashioned 2D space shooter. Complete with pew pew sound effects.

At first glance this is significantly less ambitious then my previous projects. But here is the difference. I will be implementing a learning AI. No more mindless aliens wandering on set, predictable paths. These aliens will be able to learn your play style and adapt to it.

Promised features for the game. You can hold me to this list later.
- Movement and firing of the player spaceship. Gotta put in one goal I know I can meet
- Multiple guns for the human player to choose from
- Aliens with the ability to sense and respond to their environment
- An alien overlord able to spawn aliens better suited to your play style
Stretch goals
- Powerups that can be picked up by the player or the alien
- Multiple alien spaceships driven by pilots of differing personalities
- A leaderboard fully intergrated with Facebook so you can brag to your friends
- An editon for mobile. I can put whatever I like here, something else is bound to distract me before I get this far

Speaking I which, I think I see something shinny...

Sunday, July 6, 2014

Cycling through targets on a tower defense game

Someone over on Unity Answers asked my to explain how to cycle through a list of targets for a tower defence game. The post responding became too long for a comment, so here it is.
The process in a nut shell
  1. Each tower has a trigger attached. OnTriggerEnter adds the enemy to a list. OnTriggerExit removes it from the list.
  2. Any null targets are removed from the list.
  3. The list is then scanned. The targets are scored, and the highest scoring target is returned
  4. The best scoring target is used in the towers aiming system.
If that's enough for you to implement then good on you, stop reading. If you want to see some code then read on. Note this code is untested and will probably have errors if copied straight into Unity. Also note the code is in C#. To be honest I'm not sure why Unity bothers with any other languages

The tower class

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

public class TargetFinder : MonoBehaviour  {

    // The main point of this class is to keep this target set
    // Hence we don't do anything unless something is actually looking for a target
    public Transform Target {
        get {
            return FindTarget();

    // This list holds all of the targets that are in range
    // I've chosen to populate the list using triggers
    // For a slower firing tower you could populate the list with an overlap sphere
    private List<transform> targets = new List<transform>();

    // The tower needs a trigger to determine if a target is in range
    // This code assumes the only colliders running around are enemies.
    //If not you will want to use tag checking or some other method to verify the collider is actually an enemy
    void OnTriggerEnter (Collider other) {

    // The tower removes targets from the list that move out of range.
    void OnTriggerExit (Collider other){
        if (targets.contains(other.transform){

    // This method is the work horse of the class
    // Be sure to understand this method, even if you don't get anything else
    private Transform FindTarget (){

        // First job is to see if there is anything in the list
        // No point running expensive code if nothing is in range
        if (targets.count <= 0){
            return null;

        // Now we remove everything that is null from the list
        // Null transforms get on the list when a target is in range and destroyed
        // This is called a lambda function. Don't ask how it works, but it does.
        targets.RemoveAll(item => item == null);

        // And then we check again if there are any items left
                if (targets.count <= 0){
            return null;

        // Now we check each remaining target in turn to see which one we should be aiming at
        // The code will check each possible target in turn to calculate a score
        // The score will be compared to the current best score
        // We will store the best target and score in bestTarget and bestScore
        Transform bestTarget;
        float bestScore = -999999;
        foreach (Transform currentTarget in targets){
            float currentScore = ScoreTarget(currentTarget);
            if (currentScore > bestScore){
                bestTarget = currentTarget;
                bestScore = currentScore;

        // Now our only job is to return the target we found
        return bestTarget;

    // This method is used to score the targets
    // My implementation will just check the distance from the tower, closer targets get a higher score
    // However you can make this as complex as you like
    private float ScoreTarget (Transform target){
        float score = 0;
        score = 100 - (target.position - transform.position).sqrMagnitude;
        return score;