Archive for the ‘ Unity3D ’ Category

New Aerial Combat Demo & Tutorial

[tweetmeme source=”neoRiley” only_single=false]Well, people often wonder why I tweet so little and why there are such long stretches in between.  The answer is simple enough:  I work.  Well, it’s more complicated than that, I work, I’m headcoach for my son’s football team, my daughter is in both soccer AND volley ball and I’m involved in all of them in some way or another.  That, and I just came off of a really nice game project that took 7 months of my life, and I can’t seem to do social network stuff while working and still be productive.  I don’t know how you all do it!  Anyway, I’d been wanting to do SOMETHING of a blog post just to get back into contributing to the Unity community, and so when I came off this current project, it was my turn to post something on the IR5 blog – YAY!

So, since Unite 11 is starting today and I’d promised to do a demo on this back in 09′ while speaking at Unite 09, I figured it was time to make good on my promise.  I’ve finally put it all together in a very simple, yet flushed out, demo of how I did dog fighting in The Trench Run.

Check out the post, files and demo over at infrared5.com

Enjoy!

Beast Lightmapper : Unity3D

[tweetmeme source=”neoRiley” only_single=false]I wrote a little tutorial on the Beast Lightmapping Engine now in Unity3D over on the Infrared5.com blog. It discusses more of what you can do to get quick and dirty bakes and how to essentially use the tool – nothing terribly indepth, but plenty of nice pictures :).

Rotors on top

Ambient Occlusion on shaded side

Molehill might become a fun, usable mountain

[tweetmeme source=”neoRiley” only_single=false]So, essentially, Unity has entered the Flash 3D world.  While 3D api’s (Away3D is doing an excellent job, btw) might provide a way to bring 3D to life via Molehill, Unity brings a kick-ass IDE with it.

And considering that they’re going to support AS3 right out of the bag (which they practically already do with UnityScript) as well as the other languages you can already use (I’ve become a c# fan myself), I’m hoping the resulting project from Unity will allow for maximum integration with flash projects.  I have no idea what output they intend to target (swf or project to yet be compiled by flash), but I do hope they output a project we can work with on the FlashBuilder or Flash IDE side of things.

There have been quite a few discussions about this move, and as usual, there’s 2 camps – the yay’s and nay’s.  I see it as a positive for Unity overall – they’re in the business of making tools, and they do that extremely well, and without a doubt, their developer base will broaden drastically if the resulting Flash is what people expect and need to get their work done (reference Adobe’s output for iPhone compared to Unity’s – case closed).  Case in point, I’d created a Papervision3D component for the Flash IDE a while back – it was downloaded over 450,000 times).  That tells me that people want visual solutions to 3D problems and that there’s a huge potential user base for a good Flash3D IDE.  Bringing Flash3D to the lower common denominators in the development food chain is a “good” thing.

But without a doubt, Adobe is the massive winner here.  IMO, they are walking away with much more of a win.  The one thing I’d complained about early on was that Molehill left 3D to the egg-heads who loved being the only ones who could use it.  As I’ve said before – until you bring it to a state of usability by the masses, it’s pointless and will largely be fruitless.  In other words, I felt that if the new 3D capabilities weren’t put in the hands of us lesser-folk through a common interface and language, it wasn’t going to go anywhere except for demoscene reels on YouTube.

Enter in Unity, and you just fixed all of that.  All of what I was saying and telling them they needed to achieve, they received from Unity3D (Merry Christmas Adobe).   I do wonder how Unity’s physics, Beast Light mapping and shaders will translate, but I’m guessing those are the fruits they intend to dangle in front of even the most hardened Flash 3D developer 😉

Check out the official release statement:
http://blogs.unity3d.com/2011/02/27/unity-flash-3d-on-the-web/

Extracting True Type Fonts from Font Suitcase files

[tweetmeme source=”neoRiley” only_single=false]If you’re using Unity on a Mac, you’ve undoubtedly had to import Fonts for use within your application.  Normally, you would design in Fireworks/Photoshop first, then translated that design to Unity.  After I’ve settled on what fonts I want to use, I open up Font Book and locate the fonts location on my HDD.  Of course, there are plenty of fonts that are stored in a “Font Suitcase” type of container, and as you’ve seen – Unity can’t use them.

The nice thing is, there is a tool to extract (probably several tools) the TTF files stored in Font Suitcases.  This particular one is called Fondu.

  1. Once you’ve downloaded it, extract it.
  2. Open terminal
  3. Change directory to the dir that you extracted fondu in
  4. type: ./configure
  5. type: make
  6. type: make install

This will install fondu and configure it to run.

To get your TTF, use terminal and type:

fondu [pathToYourFontSuitcaseFile]

Example:
fondu /Users/NeoRiley\ 1/Documents/RockonFlash/iPhone/Bombs\ Away/production/fonts/Eurostile

Ding. Done.  Now you have whatever TTF files you need for Unity (or whatever use you might have for them)

Have a Bandit day!

Singletons in Unity3D

[tweetmeme source=”neoRiley” only_single=false]Here are many different ways of doing singletons in Unity3D – 1) the usual way, 2) the “self contained” way and 3) the quick and dirty way 4) for you c# folks, the accessor way.

1. The Usual Way

The usual way is to have a static “GetInstance()” method on the class  that’s attached to a GameObject in the IDE, and check for an instance.  If it exists, pass it back.  If it doesn’t, return a Debug.LogWarning error about how they need to have a GameObject with the class attached to it.

public class MyClass
{
	private static MyClass instance;
	public static MyClass GetInstance()
	{
		if (!instance)
		{
			instance = GameObject.FindObjectOfType(typeof(MyClass));
			if (!instance)
				Debug.LogError("There needs to be one active MyClass script on a GameObject in your scene.");
		}

		return instance;
	}
}

2. The “self contained” way

At one point in the Trench Run game, I realized my scene was filled with quite a few GameObjects JUST for my classes. So, I developed the “self contained” singleton.  If it doesn’t find an instance, it creates its own GameObject, attaches the class instance to it via AddComponent() bingo, no need to create a GameObject in the IDE and clutter up your scene at design time.

public class Logger : MonoBehaviour
{
	private static Logger instance;
	private static GameObject container;
	public static Logger GetInstance()
	{
		if( !instance )
		{
			container = new GameObject();
			container.name = "Logger";
			instance = container.AddComponent(typeof(Logger)) as Logger;
		}
		return instance;
	}
}

3) The quick and dirty way

The quick and dirty way is simply that – setup a public static property for the instance, initialize in the Awake() method, attach to a GameObject at design time, done. In code, it’s a little more direct now with:

MyClass.instance.DoSomething();

The setup:

public class MyClass
{
	public static MyClass instance;
	public void Awake()
	{
		MyClass.instance = this;
	}
}

It’s been noted in ActionScript that accessing another method outside of the class you’re in is slower than accessing a property.  I have no idea if this is the case with Unity ( I seriously doubt it ), but with my optimization nightmares in Flash over the years, I’m usually doing #3.  Some habits just never go away (or paranoia for that matter)

Enjoy!

[**** UPDATED ****]

4. Accessor

The #1 and #2 examples above could benefit from using an accessor rather than a method – Thanks to Cliff Owen for the tip on this

public class MyClass
{
	private static MyClass _instance;
	public static MyClass Instance
	{
		get
		{
			if (!_instance)
			{
				_instance = GameObject.FindObjectOfType(typeof(MyClass));
				if (!_instance)
				{
					GameObject container = new GameObject();
					container.name = "MyClassContainer";
					_instance = container.AddComponent(typeof(MyClass)) as MyClass;
				}
			}

			return _instance;
		}
	}
}

Then, you’d just as simply as the quick and dirty way access it with:

MyClass.Instance.DoSomething();

Coming from ActionScript / UnityScript to c#

[tweetmeme source=”neoRiley” only_single=false]After writing iFly and Star Wars: Trench Run in UnityScript, I became painfully aware of the shortcomings associated with UnityScript.  Mainly that it has no decent event / delegate system to leverage.  Sure, you have event handler methods that exist in GameObject etc, but that’s a complete throw back to AS2/1 days.  I tried porting an old AS2 event dispatcher class to UnityScript (which I did successfully) but had pointed out to me by someone at Unity that it would be painfully slow.  He then suggested I consider c# and get involved with delegates.  He was right.

So, for a while now, I’ve been doing c# and loving it.  There were, however, some things that obviously caused me some discomfort and that’s why I’m writing this post.  I’ll be adding to it when ever I find new topics that apply.

First, here is a link that provides the majority of the “differences” between UnityScript and c# – I recommend this one as it really covers the basics very well.  I’ll be covering the not-so-obvious ones that made me scratch my head 😉

http://answers.unity3d.com/questions/5507/what-are-the-syntax-differences-in-c-and-javascript

Alright then, here’s the first thing to look out for:

Number = float

Coming from AS3, you’re used to Number, int, uint and for the most part, you get what they do.  When coming over to c#, there is no “Number” type.  Instead, use float.  Just think of it in the most simple terms:  “f”loat for “fraction”.  Meaning, if you know you’re number will be fractional (like 3.16) then give it a type of float:

float myScale = .5f;

Note the “f” at the end of the declaration (.5f) – that’s how you cast it as a float.  If you don’t, Unity compiler will give you an error.  Same goes for passing floats as arguments, make sure you include the “f” cast:

Vector3 pos = new Vector3(.1f, .05f, 2);  // you can add the "f" cast after a whole number if you like, but it's not necessary

If you’re doing some division or scaling math and you know the outcome *could* be fractional, both sides of the equation need to be floats or you’ll get a whole value in return.  Simple enough you might think, but I’ll bet you scratch your head at least one time on this one where you can’t figure out *WHY* it’s not calculating a remainder for you:

float i = 15f;
float j = 10f;
float value = i / j; // 1.5f

If you want to parse a string into a float or int:

int value = int.Parse(stringValue);
float value = float.Parse(stringValue);

If you want a whole number and an int from a float, use FloorToInt() – I mention this one simply because of how AS3 just doesn’t give a crap, but c# does:

int value = Mathf.FloorToInt(float n);

Event Dispatching

In AS3, everything extends EventDispatcher practically.   Everything can dispatch events, have listeners and everyone’s happy in their little event driven world.  Then you come over to Unity and realize, we’ve taken a step back into AS1/2 land. There are event handlers on GameObjects and if you declare them, then they will receive the calls – very very onEnterFrame type of stuff here.

So, given my history and experience with AS2, I naturally dusted off an old EventDispatcher class that we used to use back in the day.  Like I said above, I converted it, it worked, but was made to realize that in a performance setting, it’d be a pretty substantial bottle neck.  Still, if you’d like to see how it’s done, here you go ( now at least, I won’t feel like the time I spent on it was wasted )

EventDispatcher.js
ListenerObject.js

But now, the real deal in c# for creating an event and dispatching goes something like this:

Declare a delegate for the event. Note that I’ve created it outside the class declaration – this is so it’s available to any class:

public delegate void LoadComplete(float value);
public class MyClass
{
    //...
}

Now, create the event in MyClass:

public delegate void LoadComplete(float value);
public class MyClass
{
public event LoadComplete LoadCompleteEvent;
}

To add a listener, you add a new delegate instance with the handler to the LoadCompleteEvent event:

public delegate void LoadComplete(float value);
public class MyClass
{
public event LoadComplete LoadCompleteEvent;
    public void Start()
    {
        LoadCompleteEvent += new LoadComplete(HandleLoadComplete);
    }

    // note how the argument signature matches the delegate declaration
    private void HandleLoadComplete(float someValue)
    {
        // event handled here
    }
}

To send out the event, first check to make sure the event is not null (has listeners), then call it like a method:

public void DoSomething()
{
    if( LoadCompleteEvent != null ) LoadCompleteEvent(1.0f);
}

To remove a listener, just remove the handler from the event:

LoadCompleteEvent -= HandleLoadComplete;

Coroutines (replacement for setTimout, setInterval, Timer object)

In AS3, we’re used to setTimeout() or the Timer object to deal with waiting and looping stuff.  In the old days, we used onEnterFrame and I can still remember the arguments over which was better – setInterval or onEnterFrame.  It was a ridiculous argument, because in reality, it just depended on *what* you were doing when that even fired.  Please don’t leave comments regarding this tired and exhausted discussion which has zero relevance these days 😉

In UnityScript, you’ll be introduced to WaitForSeconds() which is really nice when coming from AS3.  In c#, however, you get a bit of a rude awakening. You begin to realize how much UnityScript lets you get away with.  Its insane.

So, here are the basics.

If you want to loop or wait a certain amount of time, you have to call a method that returns IEnumerator:

public IEnumerator DoMyBidding() {...};

Then, you have to have some sort of yield/return statement in this method or the compiler with barf all over your keyboard:

public IEnumerator DoMyBidding()
{
    yield return WaitForSeconds(1.5f);
    if( myConditionNotMet ) yield return null;  // this is how you just simply return out if you no longer wish to continue.
}

If you want to loop something:

public IEnumerator MonitorMe()
{
    while ( conditionNotMet )
    {
        // do something
        yield return WaitForSeconds(.025f);
    }
}

To call these methods, you have to use StartCoroutine():

public void Start()
{
    StartCoroutine( MonitorMe() );
}

Well, for now, that’ll get you started, and as I remember/think of things, I’ll come back and update this post with more tid-bits.  Enjoy!

New Unity3D mailing list

[tweetmeme source=”neoRiley” only_single=false]I hadn’t been able to find a Unity3D mailing list and since the Beta group was such a good resource, I went ahead and created a Unity3D Developers mailing list.  Please pass it along

http://groups.google.com/group/unity3d-developers

John

Scrolling Textarea in Unity3d – Easy explanation

[tweetmeme source=”neoRiley” only_single=false]I was looking for a quick solution to creating a scrolling textarea in Unity3D and it turned out to be more of a hunt than I thought it should have been.

So, for anyone else trying to figure it out, here’s how it works:

public void LogDebug(string msg)
 {
    Debug.Log(msg);
    traceLog += msg + "\n\n";

    // setting the "y" value of scrollPosition puts the scrollbar at the bottom
    scrollPosition = new Vector2(scrollPosition.x, Mathf.Infinity);
 }

 private Vector2 scrollPosition;
 public void OnGUI()
 {
    // we want to place the TextArea in a particular location - use BeginArea and provide Rect
    GUILayout.BeginArea(new Rect(60, 5, 250, 250));
    scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width (250), GUILayout.Height (250));

    // We just add a single label to go inside the scroll view. Note how the
    // scrollbars will work correctly with wordwrap.
    GUILayout.Label (traceLog);

    // End the scrollview we began above.
    GUILayout.EndScrollView ();
    GUILayout.EndArea();
 }

Have a bandit day!

How to do Lasers in Unity3D

I was recently asked about how the lasers were done in Star Wars Trench Run and I’d said I’d blog about that and a few other items, so here’s the first of a few.  This is the same material I covered at Unite 2009, so if you’ve seen the video or were there, there’s nothing new;)

Here we’ll cover one way of doing lasers with Unity3D that looks good and is performance friendly for the iPhone.  This isn’t meant to be exhaustive by the way, it’s just meant to be the base overview of what a laser *is* in Unity and how I managed it in terms of performance for the iPhone game.  So with that, let’s jump in to some steps on setting it up.

Create LineRenderer

0. First, Create an empty GameObject in your scene.

1.  Then, attach a line renderer component to your GameObject and position the GameObject where the tip of the laser cannon will fire from.  Why not just use a particle emitter?  This is because the ellipsoid particle emitter has a bug.  even if you set the size of the ellipsoid to 0 on all 3 axis or .0001, you will see that it starts at a random location on the z axis.  Unity acknowledged the bug.  So to fix this, since we can’t emit using the particle emitter from the cannon’s tip, we have to first show a line renderer.  Below are some typical settings you could use for a LineRenderer as a laser bolt:

Properties of a general LineRenderer for a laser

Here’s what it should look like in the Unity IDE when you get your GameObjects in place:

GameObjects with LineRenderes placed at the cannons

I created a class called LaserControl, and when I want it to show, this is literally what I do:

public var isShowingLaser:boolean = false;
function showLaser()
{
   if( isShowingLaser ) return;
   isShowingLaser = true;
   thisRenderer.enabled = true;

   yield WaitForSeconds (.05);
   resetLaser();
   isShowingLaser = false;
}

as you can see, it shows it for .05ms then hides it by calling reset laser which just does this:

function resetLaser()
{    
   this.renderer.enabled = false;
}

3.  So, then create your own class that extends MonoBehaviour and attach it to the GameObject that you added the LineRenderer to.

Create Particle Emitter

Now that we have this really nice LineRenderer laser that looks great coming from the tip of the cannon, we actually need to emit a laser to “fly” on it’s own path, right? So the concept for this is:  create empty GameObjects to server as 3D points for your emitter to “jump” to when you when it is to emit a laser from a particular cannon.  Since a particle emitter counts as 1 draw call for all of its particles, this makes it especially nice on an iPhone build.  Even better, it’s very lightweight on a web based game.

0.  Create 1 new GameObject for every cannon you have.  In this instance, I had 4 for the X-Wing, so I created 4 GameObjects with nothing in them.  Then give them names like TL, TR, BL, BR (topLeft, topRight, bottomLeft, bottomRight).

Here’s a screenshot of one of the emitter locations highlighted in the editor:

Empty GameObject serves as location for emitter later on

1.  Position these new GameObjects at the very end of the LineRenderer in your scene.  These will be the location that the emitter jumps to just before being told to Emit(1).

2.  Now, create a GameObject.  Then, with that GameOject selected, add: 1) Ellipsoid Particle Emitter, 2) Particle Animator, 3) Particle Renderer.

3.  In Particle Ellipsoid Emitter, set Local Velocity > z = -500.  This is the speed essentially.  If you want a faster laser, increase the number.  Make sure “Simulate in worldspace” is checked as this will allow emitted particles to carry on their path in world space once they’re fired.  Set the Ellipsoid to 0 on all 3 axis.  Finally, set Min Emitter Range = .0001 to make sure it fires from the closest location to the center of the GameObject as possible.  Like I said, with the bug, it’s a bit random on the z axis, but you’ll never see that in the game.  Leave the Particle Animator as is.

4.  Now the other bit of magic in making the laser is the Particle Renderer.  You’ll want to set “Stretch Patricles” = Stretched, with a length scale of 7 or so.  You can play with this number as it will determine how good your bolt looks in length.  Then set the “Max Particle Size” = .01.

Here’s a screen shot of the settings for the particle emitter and renderer ( the animator is left with its defaults ):

Particle Emitter settings

Conclusion

At this point, you have the physical objects in your scene to manage your lasers.  The last remaining step is to write a class that moves the emitter to each of those 4 emitter location GameObjects, tells the LineRenderer to show() and then emit 1 particle – BAM!  You now have lasers in Unity!

Hope this helps and hope you have a Bandit day 😉

[tweetmeme source=”neoRiley” only_single=false]

New iPhone/Web Game: Racked.

A little Rubik’s cube, a little Pool action, a little strategy, and you’ve got Racked!

Puzzles for the ages.

The cool thing about Racked is that I came up with it by putting our pool balls on a wire grid and making it up with my daughter Riley – we ended up playing for 3hrs straight the first night.  I knew right then, I had to try it on the iPhone 😉

So, I went ahead and did it in Unity3D.  At first you might think that’s a little silly given that the game is largely 2D-ish.  However, being able to code in C#, then deploy to both iPhone AND web – it was a no brainer. And as usual, the actual game engine took 8hrs to code while the UI/help and everything else took 4 weeks to finish.  My neighbor said it was his favorite game title so far – whatever that means!

So with that, check out the web version:  http://www.rockonflash.com/games/racked/index.html

And of course, if you’re into iPhone puzzle games, it’s available on iTunes ( if you do buy it, and like it, please give it a review! ):