Everyday Flash

Creative use of technology // A blog about 3D Flash and Actionscript by Bartek Drozdz

Book review “Unity Game Development Essentials”

Unity Game Development Essentials

I like books. A book is always a good thing, no matter how abundant online resources are. It’s always at hand, with all the information brought together in one place, not scattered across different sites or even worst, across different forum threads.

When I learned a couple of months ago that Will Goldstone was writing a book on Unity3D, I was pleasantly surprised. A bit later Packt, the publisher of the book, contacted me asking for a review.

In the meantime the book hit the shelves, and there was some buzz on Twitter, so there’s a good chance you’ve already heard about it. If you are still wondering whether you should buy it, keep reading.

Great for beginners

The book is written in the form of one big tutorial. The author leads us through different parts of the Unity3D IDE in the course of creating a simple game. The word “simple” is key here. Before I had the chance to read the book I went through the Unity3D official tutorial which has a similar structure. It presents us with a very cool 3D artwork and a pretty complex game to build. Compared to that, what we will create with the book is pretty basic. However, in this case: simpler means better.

After completing the official tutorial I felt I merely scratched the surface, and many parts of it were too complex to follow. The book doesn’t leave you with this feeling. You’ll be guided in creating a game but you will do it from scratch and all the steps are explained in depth.

Scripting

I assume most readers of this blog are familiar with programming. In this case you may find the code presented in the book somewhat rudimentary. One way of making it more fun is to translate the code from JavaScript into C# on the way. I did that, and I think it’s much more beneficial than just copy-pasting. At least you will read it that way.

Furthermore, Actionscript 3 programmers can find that some examples are bending the rules of strict OOP. Again, for a seasoned AS3 developer, restructuring the code in those places can be another good exercise.

The book covers obviously more than just scripting. Among other topics, I particularly enjoyed the chapters on particle systems and on 2D GUI (as you will find out, 2D GUI is the weird part of Unity)

Other ressources

An indispensable companion of the book is the Unity scripting reference. The docs are solid and in most cases you’ll find what you’re looking for. Not always however, and if you feel you need more info I recommend to search the forums. I am not a fan of forums overall, but I must admit that the Unity3D forum is a pretty good resource.

A remark on the Unity3D documentation

A bit off-topic, but I will take the occasion to rant about the Unity3D scripting documentation. Not about the content, but about the form.

In the Unity3D docs the list of classes is sometimes placed on the left column, sometimes in the middle. Sometimes they are listed in alphabetical order, sometimes presented in an inheritance structure. Every property and method is presented on a separate page, which is a big waste of space given the fact that most of them have max 2-3 lines of description. It leads to constant back/forward clicking when exploring the API. And it might get even worse when Unity will introduce namespace support.

It would be cool if the docs followed the good old Java standard, where the list of classes is always in the same place, always accessible and in alphabetical order. The properties and methods are listed in one big table, which is also much easier to browse.

OK, enough complaining, now back to the book…

Conclusion

If you want to get into Unity, it’s probably a good idea to buy this book. You’ll get yourself a decent introduction to the main aspects of the software. Remember that you won’t learn any advanced stuff like stucturing code in large projects, writing custom shaders or making advanced physics simulations. The important thing is that the book explains all the basics leaving you well prepared to explore the rest. I enjoyed reading it and I learned quite a lot!

FOTB’09 presentation: 3D Bowling demo

Video of 3D Bowling Demo, Flash on the Beach 2009

UPDATE Nov 2009 There is a better quality video posted by John from Flash On The Beach. It is available here: http://vimeo.com/7292505.

As I promised during my "3 minutes" in Brighton, I publish all the sources of my presentation. I added some comments in the code and removed the part with the slides.

Here's also the demo and a video of the mini-session. The demo is pretty rudimentary - I made so because I wanted to keep things simple during the presentation. I hope that it will be a solid base for someone who wish to create a full featured bowling game in Flash.

There were a few other implementations of a bowling game in JigLibFlash and Papervision3D. Initially, guys a Blitz Agency published a few interesting experiments with JigLibFlash, including a simple bowling simulation. Devon O. Wolfgang has written a great tutorial about building such a game on Tech Labs - be sure to check it out. I found it only after the presentation and since the tutorial explains a lot of things in details I felt like I was reinventing the wheel here. But hopefully there are still a couple of things I can add.

Thanks to the new plugin API we developped some time ago, setting up a scene with JigLib and an 3D engine has got a bit less complicated. However, tweaking the engine can be a hell. Here's a few things I found out:

1. Simulation speed

When you create the physics engine instance, the default speed of the simulation is 1. This is very slow and unrealistic. It will look much more natural if the speed is increased. Beware however - at higher speeds the collision detection system can be very inaccurate and result in objects running through each other without any collision being detected. I don't think there is a single setting that works fine in every situation, but for this case 9 worked fine for the regular speed simulation, and 2 for the "slow speed". You should always try different settings.

2. Mass

Each rigid body has a mass property. It's easy to forget about it since it has a default value and it never complains if you don't change it. However, setting the masses right is crucial for a realistic simulation. In real world object have different masses, and so they should in a simulation. This is particularly important for a bowling game, where the ball is pretty heavy and the bins are not (I guess... has anyone ever had a bowling pin in his hands?) The trick is that the masses are relative to each other, so the more different objects you have the more you need to tweak the masses to get the results right. Also remember the effect of any forces applied to an object is related to it's mass.

3. Physics material

Each rigid body has a property called material which is an instance of the MaterialProperties class. It has two properties: friction and restitution. I found out that playing with this values has a quite big impact on the simulation. Ex. setting a high value of the restitution results in the object becoming bouncy - I used this for the ball in my older ping-pong example. In the bowling demo I used lower friction on the ball to make it slide more - just as a real bowling ball does.

4. Object rotation

Once a DisplayObject is wrapped into a physics rigid body you can't rely on it's rotationX, rotationY and rotationZ propeties anymore - because they are not being set. The physics engine sets the transformation matrix directly on the DisplayObject, so if you need to check it's rotation you need to extract it from the matrix. Fortunately, there's an easy way to do this:

Actionscript:
  1. var p:DisplayObject3D = physics.getMesh(pins[i]);
  2. var h:Number3D = Matrix3D.matrix2euler(p.transform);
  3. // h.x is the rotationX of the object in this case.

5. Object activity

As a result of multiple forces being applied to an object and multiple collisions sometimes the objects are left in a state where the shake a bit endlessly. This can also happen when the objects are initially positioned. Calling the RigidBody.setInactive() will fix that. And you can call more than once.

Important conclusion: tweak, tweak, tweak...

It is generally agreed that hardcoded ("magic") numbers are not a good coding practice. However in 3D animations, and especially with physics the important thing is not the beauty of the code, but the what you see at the end. If you browse the source code from this demo you will notice that I not only hardcoded a lot of values, I even left ugly lines like that:

Actionscript:
  1. force = (speed == 9) ? 5000 : 3000 * 8 * 4;

In fact this is what I like the most in doing all those demos and experiments - the moment when code stops being just a list of instructions for the machine and becomes an art of making things look good by adding little tweaks here and there. If you tend to write very clean code and use all possible standards and conventions, from time to time make it ugly... you'll see how good it feels :)

I hope that this few tips will help you with your next JigLib project!

Last but not least, I'd like to say thanks to everyone who woke up early to see the Elevator Pitch session. It was a great experience being there and talking to you. The Brighton Dome packed with people can be intimidating and 3 minutes is not much time, so there was no place for mistakes. Fortunately, the FOTB technical crew made it all seamless. Great job guys!

Finally, I would like to give a special thanks to John Davey for inviting me to Flash On The Beach and for making this great conference happen!

Hope to see you next year!

Speaking at Flash on the Beach ‘09

Flash on the Beach 2009

I extremely happy to announce that I will speak at this year's Flash on the Beach in Brighton. It starts two weeks from now and if you haven't already got a ticket it might be too late, because they're all sold out (sorry).

It will be my first appearance on such major Flash event. I am taking part in the Elevator Pitch session, which features 20 speakers (!) in 1 hour - 3 minutes each. So it won't be a long presentation, but be sure - it will be intense. I will show a new 3D Flash experiment made especially for FOTB. The session takes place on the second day of the conference, Tuesday 22nd at 9AM in the Brighton Dome. Hope to see you there!

On a related note: if you live in Antwerp, on September 16th I will be also speaking at an event organized by my friends at Mr. Henry. I'll present some of my new and older experiments and talk about 3D in Flash in general. You can find more info about this here.

Getting started with C# for Unity3D

C#

Unity3D offers a choice between 3 different programming languages: JavaScript, C# and Boo. Each of them has its pros and cons, but for me C# almost immediately came out as a clear winner. That is because it is fully object oriented and it's syntax is similar to Java and Actionscript 3, both of which I am experienced with. However, before I started to play with Unity3D, I never wrote a single line in C#, so I had to learn it from scratch.

As you probably know C# was originally developed by Microsoft and is widely used in the .NET framework as well as in Silverlight development. It is important to understand however that learning C# for Unity3D is not the same thing as learning the .NET platform. In fact you don't have to know anything about .NET to use C# with Unity3D.

While I use all kinds of online documentation, a book is often the best companion, so I thought buying a good C# book would be in order. It turns out that the small O'Reilly C# Pocket Guide is exactly what one needs. It is absolutely unnecessary to buy a 500 page C# bible, as most of the stuff in those books is related to .NET and is not applicable to Unity3D at all.

Of course the book alone is not enough. You also need the Unity3D scripting reference. All the examples in the docs are given in Javascript only. But don't worry, they are easy to translate once you get used to.

C# is a very elegant and powerful language. It's dot-syntax is based on Java, so if you come from a Java background you'll quickly feel comfortable with it. There are a few differences though. The most striking difference is the convention to start property and method names with an uppercase letter. I guess it comes from Visual Basic. I am not a fan of this convention, but it's better to use it and have a consistent code rather than fight it.

The list of all C# features is so long, that it makes AS3 look poor in comparison. C# is really like Actionscript on steroids. I suppose the next version of Actionscript will have at least some of those implemented, so it's good to know about them. Here's a list of my favorites.

Operator overloading

This is the coolest one by far! It allows to define custom actions for common operators like +, -, * or /. The best illustration of this feature comes with vector addition. In Actionscript, to get a sum of 2 vectors you need to write something like this:

Actionscript:
  1. var c:Vector3D = a.add(b);

This is not very nice, and becomes almost unreadable if more than two vectors are added. In C#, thanks to the overloaded + operator it looks like this:

C#:
  1. Vector3 c = a + b;

This is much more readable and elegant, isn't it? It goes without saying that the 3D vector implementation in Unity3D has all the operators overloaded. In case you want to do it yourself however, the implementation of operator overloading is very simple and in the above case could look something like this:

C#:
  1. public static Vector3 operator + (a:Vector3, b:Vector3) {
  2.    return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
  3. }

There are some simple rules: the operator function must always be static and must return an object of type it is defined for. However it can take any type of parameters. This allows to define operator overloading for adding or multiplying vectors but also for multiplying vector by a scalar or multiplying vectors by matrices. In fact this can be achieved thanks to another C# feature - method overloading.

Method overloading

Method overloading allows to define multiple methods with the same name provided that they take different parameters. It works with regular methods and with constructors as well. If there a multiple ways to create an object you can define multiple constructors to satisfy each case. As mentioned above it works with operators too.

A good example of method overloading in Unity3D API is the 'Transform.Rotate()' method. It has has been overloaded 3 times with different ways to specify a rotation:

C#:
  1. void Rotate (Vector3 eulerAngles, Space relativeTo)
  2. void Rotate (float xAngle, float yAngle, float zAngle, Space relativeTo)
  3. void Rotate (Vector3 axis, float angle, Space relativeTo)

You can either pass a vector of angle values, three floats - one for each axis, or a single angle combined with a rotation axis. This is only logical to call it 'Rotate' every time because this is what the method does at the end.

Actionscript has default parameter values, which in some cases can simulate method overloading but they are not quite as flexible as that.

Getter/setter syntax

C# has a very concise way of declaring parameters. While in Actionscript it takes two functions - one for 'get' and one for 'set', in C# it can look like this:

C#:
  1. public float Size { get; set; }

In this case the compiler automatically adds a private member for this property and there isn't anything else you need to do. Of course such a parameter is not very practical, so here's a more complex code, involving a public getter and private setter:

C#:
  1. public float Area {
  2.     get { return size * size; };
  3.     private set { size = Mathf.Sqrt(value) };
  4. }

You will also notice that neither the 'function' nor the 'var' keywords do not exist in C#. In that C# closely follows Java. This is good because both these keywords are completely redundant and do not add any information to the code.

Among other interesting features I recommend to explore indexers, generic types, structures and enumerators all of which are covered in depth in the pocket guide mentioned above but also in the many online C# tutorials.

Editing C#

There are multiple editors that support C#. Microsoft offers a great and free editor called Visual C# Express Edition which features code completion, but is Windows only (obviously). For a Mac there's Mono Develop which looks very powerful, but is not very stable yet. Unfortunately the C# plugin for Eclipse is completely unstable for the moment, and I wouldn't recommend it. On the other hand, it is still in alpha so let's give it some time. Of course there's always TextMate.

Last but not least there's Unitron - the Unity3D default editor. It is not very popular among developers, and I saw people complaining about it being too basic. I don't share this opinion. While it ain't no FDT, it's pretty solid, very stable and has basic auto-completion. The trick is auto-completion is turned off by default (why?). To turn it on go to 'Preferences' and you'll find it at the bottom of the 'General' section. With that, I'm sure that Unitron is enough to get started.

Most of us know JavaScript from the browser environment. JavaScript is often the first programming language people ever used. If this is the case, you may be tempted to just use JS with Unity3D right away and not bother learning anything new. After all, as far as Unity3D is concerned, anything that can be done with C# can also be done with JavaScript.

However in the long term, C# offers better control over the code, full OOP support, strong typing and a lot satisfaction of mastering a robust programming language, so the extra effort is worth it. Plus, for a seasoned AS3 developer, mastering C# is a matter of a couple of weeks anyway, so go ahead and try it out!

UPDATE March 2010. Here's a new post about C# and Unity3D:
Loading and manipulating images in Unity3D
(more coming)

My presentation at Warsaw Flash Camp 2009

More pictures from Warsaw Flash Camp 2009

On June 9th the Polish Adobe User Group organized a Flash Camp in Warsaw. It was the first meeting of this kind in Poland. I had the privilege to be one of the speakers. It was a one day event featuring 6 sessions all related to Flash & Flex. It aroused great interest in the local Flash Community and more than 300 people attended

We kicked off in the morning with a very comprehensive presentation by Serge Jespers on the Flash Platform. Serge went through a lot of interesting projects including some of the best Augmented Reality examples. He also showcased his favorite AIR applications. Apparently AIR is not used only for Twitter clients! But seriously, I neglected this technology so far, but I promised myself to fix this in the near future. I'm looking for some ideas for a simple AIR app now... a Collada viewer maybe?

Next, the Platform Evangelist from Poland, Piotr Walczyszyn gave us an insightful presentation on Flash Catalyst and the new Flash Builder. I use FDT to do all my Flash stuff for some time now, so all the things he presented were totally new to me. I must say I was surprised how fast and efficient the new workflow is. Things like working directly with PSD files in Catalyst look great (how many hours have I spent "cutting" PSD files and importing them into Flash!) He build a complete application connected to a database without writing a single line of code! It was amazing... and a bit frightening too ;)

Wojtek Ptak made a great presentation about building large scale RIA's. Usually this kind of applications are not my primary interest but Wojtek showed us some really inspiring stuff and it was a pleasure to listen to him speaking.

Unfortunately I could not attend the other sessions, because I was rehearsing my own. It was my first public presentation, so I was pretty excited but also a bit nervous, especially that I did not expect such a huge crowd.

During my session, I focused on 3D in Flash (of course!). By showing some new and old demos I tried to explain the fundamental concepts of 3D graphics and how they are implemented in Actionscript. After my session I had a few minutes to answer some questions. Most of them were about Papervision3D, and the nature of those questions clearly showed that they were coming from very experienced developers. I did my best to answer all of them.

Overall it was a great experience, and I'd like to thank the organizers for inviting me. I like the idea of public speaking. It's a great way to share some thoughts and knowledge, but also, most importantly, to meet interesting people. I feel it nicely complements my blogging experience, so from now on I'll be looking for more speaking opportunities.

Unity3D is awesome!

How I learned to stop worrying about plugin penetration and love Unity3D

I started this blog almost 2 years ago with an idea to explore the world of 3D in Flash and learn new stuff on the way. I quickly fell in love with Papervision3D. It offered a whole new world of possibilities for someone like me - bored with buttons & dropdowns and not particularly interested in building Flex-type applications.

Unfortunately the performance limitations of Flash Player prevented me from going far beyond the demos I posted on this blog. Creating a solid piece of 3D in Flash, with a decent frame rate is either impossible or requires an insane amount of code optimization. It often means resorting to low level programming. I think it is dangerous, because it's easy to loose track of the overall picture then. I feel that this is what happened to me the last few months.

I sure heard about Unity3D before, but, as it often happens, I did not have time to take a closer look. I applied for the Unity 2.5 beta test program back in February. I was accepted and got a 30-day copy of the software. What happened next? I opened it only once before the trial expired.

It's just hard to move to another software/platform when you are so completely immersed in Flash. Unity3D ended on my perpetual to-do list alongside with so many other things. I am sure many of you feel the same way.

A new toy

Recently I bought a Macbook Pro. My first Mac ever! A friend suggested that I move all my projects and workspace to the Mac immediately to make the transition fast. Unfortunately I had some difficult and urgent projects to finish, and ultimately I decided to stick with Flash on the PC for a while.

I had to do something with the Mac then... and that's where Unity3D comes in. Additionally, this time I decided to buy a license, thinking that spending those 150 EUR extra will make me even more motivated.

After just a few hours I was amazed. And I mean AMAZED! You can check the Tropical Paradise demo if you haven't seen it yet, download the trial copy and start exploring the 3D Game Tutorial to see what I mean.

It's not only how fast the 3D rendering is. Unity3D has a very intuitive interface organized around a simple and clear concept. I can literally see myself doing 3D games in a matter of weeks from now. Doesn't take long to realize the sad truth that Flash is far behind in almost every aspect.

The myth of high penetration

I do not want to do a list of pros and cons or some Flash vs. Unity3D comparison here. For a person who wants to do 3D for the web Unity3D is the winner by knockout and it makes no sense to elaborate on the subject.

However, there is one common argument against Unity3D. It's the low penetration rate of the web plugin. While Flash Player is at 98%, Unity3D is probably at < 1%. Aye! That sounds bad, doesn't it? I thought so too, but I made some thinking and researched a bit. Now please consider these points:

  • Unity3D plugin is only ~4MB and it's installation is seamless. In most cases, it doesn't even require browser restart. Thanks to this it has a high successful-install rate, which means it's share of the market will be quickly growing. You can read a whole article on this topic here.
  • Content created with Unity3D can be visually and interactively much superior to anything you can do with Flash. This will convince people that the little extra effort required to install the plugin is worth it.
  • Most important argument: people access content from different devices. There are mobile phones, consoles, multi-touch interfaces etc. PC is no longer the king. Unity3D can be published for two of the most successful platforms out there: iPhone and Wii. "Web penetration" has no practical meaning in this case.

So, if you think Unity3D is not worth looking at because of the low penetration of the web plugin, think again!

This blog note may seem emotional. It is! I feel I have discovered the perfect technology, that I have been looking for and I just wanted to share. Now I need to master Unity3D as quickly as possible. On my way I will certainly discover it's flaws... it must have some. Maybe later I will find a more objective way to compare Flash and Unity.

Flash is much more than 3D and there are multiple directions it is evolving in. I am not predicting "the end of Flash" or anything like that - it would be ridiculous. Unity3D on the other hand, with all it's coolness is still the new kid on the block. It might be a huge success but it might as well share the fate of Wild Tangent and Shockwave players (I hope not!).

One thing is sure: if you are into 3D, you can't miss it!



  • FITC10