Archive for the ‘ Unity3D ’ Category

SoundCanvas Introduction – Managing Audio in Unity5

ScreenShot

During the production of our internal game project at DreamSocket, I started creating a tool to bridge the gap between the new audio Mixer technology in Unity5 and the audio clips themselves.  The mixer and snapshots features of Unity5 are brilliant for designing your sound in a scene – everything you could ever want to really bring the sound design of your game to life.

The problem is, and has been for along time with Unity, how to manage a scene’s audio clips?  These are clips that *have* to be added to an object or scene physically rather than programmatically.  I say *have* to, but that’s really not the case from a developers point of view.  We can add sound and design the sound programmatically to our hearts content.

The problem is, we’re the ONLY ones who can work with the sound in a scene at that point and a sound designer is essentially at our mercy to implement his work accurately.  And to be honest, doing sound design with a “listen/stop/adjust code/play/repeat” model isn’t going to probably yield the best results.  Being able to mix and manage at design time in the editor is by far a much better solution.

This is where SoundCanvas comes in.

SoundCanvas is not only an audio API for controlling your game’s sound, but a Unity editor extension that allows you (or anyone else on your team) to design your scene’s audio in a central, easy to use, interface.

Some of the features:

  • Easy to use API for controlling sound playback, use snapshots for transitions and globally manage your games audio
  • Assign single audio clips to multiple game objects using tags
  • Assign multiple audio clips to single or multiple game objects
  • An easy way to marry audio clips with mixer groups
  • Change the target of an audio clip by simply changing what tags it targets
  • Creates and manages it’s own enum file for easy of use with the sound API

Currently, SoundCanvas is in development, but our goal is to release it via the Unity Asset Store as a free Editor Extension.  So until then, we’d love to hear feedback and reaction to what we have so far.

Have a bandit day!

Showing camera view frustrum in Scene view

We’ve been working on a 2D game in Unity3D and I’d written this a while back to show the view frustrum of the camera in the scene view and had been meaning to post it:

Yellow wireframe outlines view frustrum. Top is scene view, bottom is game view

Create a new c# script in Unity and call it “DrawCameraViewFrustrum.cs”.  Copy/paste the code below and attach it to your camera object in your scene.

using UnityEngine;
using System.Collections;

public class DrawCameraViewFrustrum : MonoBehaviour
{</pre>
#if UNITY_EDITOR
	public static Vector2 GetMainGameViewSize()
	{
		System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor");
		System.Reflection.MethodInfo GetSizeOfMainGameView = T.GetMethod("GetSizeOfMainGameView",System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
		System.Object Res = GetSizeOfMainGameView.Invoke(null,null);
		return (Vector2)Res;
	}
	#endif

	public static DrawCameraCull instance;
	public Color color = new Color(0.1f, 0.14f, 0.8f, 0.5f);
	public bool isZoomed = false;

	protected float unitsWidth = 8.95f;
	public float zoomedOrthoSize = 2f;

	protected float camVertExtent;
	protected float camHorzExtent;

	protected Transform playerTransform;
	protected Camera cam;
	protected Vector2 topRightCorner;
	protected Vector2 screenExtents;

	void Awake(){
		instance = this;
	}

	public void Start(){

		cam = GetComponent&lt;Camera&gt;();

		topRightCorner = new Vector2(1, 1);
		screenExtents = cam.ViewportToWorldPoint(topRightCorner);

		CheckCameraView();
	}

	public void ToggleZoom(){
		isZoomed = !isZoomed;

		if( isZoomed ) {
			cam.orthographicSize = zoomedOrthoSize;
			UpdateExtents();
		} else {
			cam.transform.position = new Vector3(0,0,-10);
			CheckCameraView();
		}
	}

	public void Reset(){
		isZoomed = false;
		cam.transform.position = new Vector3(0,0,-10);
		CheckCameraView();
	}

	protected float camX;
	protected float camY;
	protected float leftBound;
	protected float rightBound;
	protected float bottomBound;
	protected float topBound;
	public void Update(){

	}

	#if UNITY_EDITOR
	public virtual void OnDrawGizmos()
	{	
		//if( Application.isPlaying ) return;

		CheckCameraView();

		Gizmos.color = color;

		Matrix4x4 temp = Gizmos.matrix;
		Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
		if (GetComponent&lt;Camera&gt;().orthographic) {
			float spread = GetComponent&lt;Camera&gt;().farClipPlane - GetComponent&lt;Camera&gt;().nearClipPlane;
			float center = (GetComponent&lt;Camera&gt;().farClipPlane + GetComponent&lt;Camera&gt;().nearClipPlane)*0.5f;
			Gizmos.DrawWireCube(new Vector3(0,0,center), new Vector3(GetComponent&lt;Camera&gt;().orthographicSize*2*GetComponent&lt;Camera&gt;().aspect, GetComponent&lt;Camera&gt;().orthographicSize*2, spread));
		} else {
			Gizmos.DrawFrustum(Vector3.zero, GetComponent&lt;Camera&gt;().fieldOfView, GetComponent&lt;Camera&gt;().farClipPlane, GetComponent&lt;Camera&gt;().nearClipPlane, GetComponent&lt;Camera&gt;().aspect);
		}
		Gizmos.matrix = temp;
	}

	#endif

	protected void OnLevelWasLoaded(int level) {
		CheckCameraView();
	}

	protected void CheckCameraView(){

	}

	protected void UpdateExtents(){
		//if( !Application.isPlaying || Application.loadedLevel == 0 ) return;

		// update the extents
		camVertExtent = cam.orthographicSize;
		camHorzExtent = cam.aspect * camVertExtent;

		leftBound   = -screenExtents.x + camHorzExtent;
		rightBound  = screenExtents.x - camHorzExtent;
		bottomBound = -screenExtents.y + camVertExtent;
		topBound    = screenExtents.y - camVertExtent;
	}
<pre>}

UniSWF to Unity3D – Character Animation

This is a short tutorial I did for our internal group at DreamSocket on how to use a MovieClip with timeline animations (in this case, a character animation), with UniSWF, in Unity3D.  Thanks to Trevor Van Meter for the character animation for this demo!

How to split animations via script in Unity3D Editor

If you’ve purchased a set of 3D models (let’s say, a pack of zombie models) that come with an animation list, then you know what a pain it is to sit and add each animation name/start/end frame in the editor.  It’s not always necessary, but in this particular occasion, I had to do it for each model.

Thanks to someone over at Automation Systems Group, I was able to use one of their scripts ( with a slight edit for an error due to legacy code ) in the editor to add the animation clips via a text file.

The code below explains everything essentially, including how to format the txt file:

 

// FbxAnimListPostprocessor.cs : Use an external text file to import a list of

// splitted animations for FBX 3D models.
//
// Put this script in your "Assets/Editor" directory. When Importing or
// Reimporting a FBX file, the script will search a text file with the
// same name and the ".txt" extension.
// File format: one line per animation clip "firstFrame-lastFrame loopFlag animationName"
// The keyworks "loop" or "noloop" are optional.
// Example:
// 0-50 loop Move forward
// 100-190 die

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System;

public class FbxAnimListPostprocessor : AssetPostprocessor
{
 public void OnPreprocessModel()
 {
 if (Path.GetExtension(assetPath).ToLower() == ".fbx"
 && !assetPath.Contains("@"))
 {
 try
 {
 // Remove 6 chars because dataPath and assetPath both contain "assets" directory
 string fileAnim = Application.dataPath + Path.ChangeExtension(assetPath, ".txt").Substring(6);
 StreamReader file = new StreamReader(fileAnim);

 string sAnimList = file.ReadToEnd();
 file.Close();

 if (EditorUtility.DisplayDialog("FBX Animation Import from file",
 fileAnim, "Import", "Cancel"))
 {
 System.Collections.ArrayList List = new ArrayList();
 ParseAnimFile(sAnimList, ref List);

 ModelImporter modelImporter = assetImporter as ModelImporter;
 modelImporter.clipAnimations = (ModelImporterClipAnimation[])
 List.ToArray(typeof(ModelImporterClipAnimation));

 EditorUtility.DisplayDialog("Imported animations",
 "Number of imported clips: "
 + modelImporter.clipAnimations.GetLength(0).ToString(), "OK");
 }
 }
 catch {}
 // (Exception e) { EditorUtility.DisplayDialog("Imported animations", e.Message, "OK"); }
 }
 }

 void ParseAnimFile(string sAnimList, ref System.Collections.ArrayList List)
 {
 Regex regexString = new Regex(" *(?<firstFrame>[0-9]+) *- *(?<lastFrame>[0-9]+) *(?<loop>(loop|noloop| )) *(?<name>[^\r^\n]*[^\r^\n^ ])",
 RegexOptions.Compiled | RegexOptions.ExplicitCapture);

 Match match = regexString.Match(sAnimList, 0);
 while (match.Success)
 {
 ModelImporterClipAnimation clip = new ModelImporterClipAnimation();

 if (match.Groups["firstFrame"].Success)
 {
 clip.firstFrame = System.Convert.ToInt32(match.Groups["firstFrame"].Value, 10);
 }
 if (match.Groups["lastFrame"].Success)
 {
 clip.lastFrame = System.Convert.ToInt32(match.Groups["lastFrame"].Value, 10);
 }
 if (match.Groups["loop"].Success)
 {
 clip.loop = match.Groups["loop"].Value == "loop";
 }
 if (match.Groups["name"].Success)
 {
 clip.name = match.Groups["name"].Value;
 }

 List.Add(clip);

 match = regexString.Match(sAnimList, match.Index + match.Length);
 }
 }
}

NGUI for Unity

After interviewing with a few unity3D shops,I was hit with the same question every single time: “do you have NGUI experience?” – to which I replied “no, but I’m sure I can pick it up”. They didn’t share my optimism 🙂 Enter in NGUI for Unity!

What I love about e-books these days is their size and how concise they can be, and this book delivers not only on both counts, but sets you in motion with a very real world example project that covers a great portion of the capabilities of NGUI. Everything from the wizards to widgets to creating atlas’ and fonts is covered. The book isn’t exhaustive in its explanations but IS thorough in pointing out the features and properties of all the components it covers – which makes it easy to follow along with in the examples.

The author gets right to the meat of the matter immediately walking you step by step through the sample project. It helps to have Unity3D experience and you’ll have to understand the basics of how unity works with prefabs and code as this book is targeting unity devs looking for a solid UI framework. It IS written in a very practical manner so even a complete beginner could get something out of it.

Now, in thinking back about my response to potential clients about just “picking NGUI up”, I see how deep the framework really is. It’s much more than just a set of UI components, and this book really brought me up to speed in a very short amount if time – excellent work!

Find more information here

Starting New!

PinkyIconWell, it’s time to start fresh on a few fronts!

First, I’m now looking for a new position in Unity3D with another shop.  My time with Infrared5 has finally concluded after 6+ wonderful years there!  So, if you know of any shops looking for Unity3D developers or have need of a contractor, please drop me an email!

Second, Save Pinky!  has received MANY updates and is in for review by Apple right now [update: it’s just been approved and is live in the app store now!]- I’m hoping it’ll go live by mid January at the latest.  But the downloads continue to astonish me!  We’re getting well over 150 a day most days and the GameCenter leader board count is well over 12,000!  What’s even more, there are TWO players who have posted scores over 1000!!!!  what?!  Incredible!!  My high score is 635, and I can’t imagine hanging on for another 800 holes!!  But I’m so glad people have enjoyed it like I have, and with the new ramps and balls, they should have even more fun with it.

Third, I updated my blog to a new more clean look and cleaned up some of the images/icons on the right menu for my iOS game titles, and I have made a commitment to start adding more content related to C#, Unity and Flash this coming 2014!

Enjoy the screenshots from my work in the past 6+ years with Infrared5!

This slideshow requires JavaScript.

GetRandomInDonut() – Random location in a donut area

[tweetmeme source=”neoRiley” only_single=false]The scenario is: you’ve got a player object, and you want to spawn enemy characters away from the player, but within a range.  Basically, within a donut area, right?

using UnityEngine;
using System.Collections;

public class Utils
{
    public static Vector3 GetRandomInDonut(float min, float max)
    {
        float rot = Random.Range(1f, 360f);
        Vector3 direction = Quaternion.AngleAxis(rot, Vector3.up) * Vector3.forward;
        Ray ray = new Ray(Vector3.zero, direction);

        return ray.GetPoint( Random.Range(min, max) );
    }
}

To use it, just call it with the minimum and maximum distance away you want your new position to be. Then add it to the transform of where your player’s spawn point is:

public void LoadCharacters()
{
    // add the transform's position since the returned position is from a location of Vector3.zero
    Vector3 pos = transform.position + GetRandomInDonut(20f, 50f);
}

Unity Flash Export – Now Available in Open Beta

[tweetmeme source=”neoRiley” only_single=false]Just released – the Open Beta developer preview of 3.5 which, as you may have anticipated, includes the Flash Exporter.  For those of you who have spent your Flash 3D lives without a decent editor, prepare to soil yourselves.  Come to the dark side and see where I’ve been living (and loving) for the past 3yrs!

Unity Open Beta

Copteropolis – Canyon Run

[tweetmeme source=”neoRiley” only_single=false]

It’s nearly ready!

Copteropolis (was StuntCopter): Coming Soon

[tweetmeme source=”neoRiley” only_single=false] I’ve been BUSY!  Between IR5 work and my kids sports, I’ve had very little extra time to work on projects.  However, a little while back, I got the urge to breakout Battlefield 1942 and install the Desert Combat Mod so I could fly the helicopters again!  If you played the game, then you know – it’s helicopter controls were the BEST EVER!!  It took me a month to figure out HOW to fly them because of the rudder controls with pitch/roll combined.  But once a friend of mind showed me, I OWNED EVERYONE.  Even the jets feared me.  I loved flying the helicopters in that game!

Well, I finally snapped and decided I was going to try and recreate the controls and feel and see how hard it was to create that sensation in Unity.  It was definitely a bit of a labor, but I had it dialed in in about a weeks time and it rocks \m/

So, of course, I decided to create a game – StuntCopter!

Copteropolis

The Refinery Compound

The story line is that we have a helicopter academy and we’ve secured 2 abandoned locations, so far, for helicopter training: Copteropolis and The Old Refinery Compound.  As a pilot, you’ll have the ability to free fly around both locations and learn how to pilot the helicopters.  Take you’re time as you learn in the slow but sure Huey.  Taking off, landing and turning all sound very simple until you have to work with throttle and rudders along with pitch and roll at the same time!  As you become more comfortable and consistent, move up to T.C.’s chopper of choice -Hughes 500D.  It’s quick, is very touchy with the controls, but can take harder landings because of the height of it’s landing gear, and might be the perfect choice for those more detailed courses.  You’ll also have access to the more recent BO 1o5 helicopter – you may have seen it doing back flips on youtube!  This heli is FAST!  Not as nimble as the 500D, but if you’re looking for flat out speed, this is the copter of choice.

And don’t worry – I put in noob controls so you can fly it with 2 thumbs.  However, you’ll be limited to certain tracks and courses, so you just might want to man up from the beginning and fly with the true controls.

There are 3 competition types:

  1. Rescue:  In Copteropolis, you’ll be trained to locate accidents and air lift victims to the nearest hospital!  The closer you land to the middle of the landing circle, the sooner the victim is loaded and you can fly to the hospital.  How fast can you save everyone?
  2. Race:  In Copteropois and The Refinery Compound you’ll have to race through obstacles to beat your best times.  You’ll be ghost racing against yourself!
  3. Car Chase:  In Copteropolis, you’ll have 2 choices of difficulty for a car chase:  OJ’s bronco (easy), or the Ferrari (difficult).  The goal is to block intersections before the car gets to them to force them up on the freeway down to the either end. You have to master the controls to even think of attempting either vehicle chase!

The game functionality is nearly complete and I’m working on create more levels for ghost racing, but it’s nearly there!  I’ll post about it again once it hits the app store, but I’m also considering releasing it as a web game, so I’ll be posting details about that soon!

[UPDATE] – thanks to someone being more heads up than me, it was discovered that an iPad game called “StuntCopter” has just been released! I’m changing the name and for now, it’ll be “Copteropolis”.  Suggestions are welcome!

Until then check out the first demo video featuring footage from all 3 competition types:

Screens: