Archive for July, 2011


Unity3d 3.4 Mono develop and dark themes

With the latest Unity3d 3.4 update they have set MonoDevelop as default. I’m going to give it a try and compare how the experience is working with mono develop compared to my usual textmate. One thing the compels me is the Intellisence which might come in handy and save me a lot of unity reference lookups to see what the right types are for the method call. Though before I could start using Mono Develop I had to get rid of the whiteness ! As mono develop uses GTK+ you should be able to just drop in a gtk theme and be fine. Alas it was not as easy as this :/

You can download some dark themes I found including my howto in one package here :Β http://dl.dropbox.com/u/1723477/darkmono.zip

DarkMono

After some experimenting I found something that works fairly well for me. Follow along if you are interested πŸ˜€

Β 

Download a GTK+ theme to your liking. You can use sites like : http://gnome-look.org/
Make a new directory in your homedir called .themes :Β mkdir ~/.themes
Extract your downloaded themes to this directory.

After that you :

– Start Mono develop

– select visual style -> Interface theme ->Β  clear looks black blue

– select text editor -> syntax highlighting -> irBlack

– Quit Mono develop

Β 

ThenΒ either backup or remove this directory and file

mkdir ~/default_monotheme
sudo mv /Applications/Unity/MonoDevelop.app/Contents/Frameworks/Mono.framework/Versions/2.6.7/share/themes/ ~/default_monotheme
mv /Applications/Unity/MonoDevelop.app/Contents/Frameworks/Mono.framework/Versions/2.6.7/etc/gtk-2.0/gtkrcΒ ~/default_monotheme

Β 

Then start mono develop again, and now your eyes are at ease πŸ™‚
Happy coding everyone !

An other weekend passed, so an other update is in order πŸ™‚

The planning for this weekend was to add an other magic effect, a targeting system, GUI element reflecting the target and fix some of the animations.

Targeting System :

As it is now we can freely shoot fireballs and hope we hit our target. But for our next skill we actually need to focus on a target, thus it was time to create a nice targeting system. This actually took several tries to get it right, or at least, we hope it’s right now πŸ˜‰

The first iteration of the target system worked like this : As our characters have a FieldOfView that helps with detecting if an object can actually be seen by the character I thought this would be a nice point to start with. Though pretty soon I found out that you can only check of a certain gameObject’s position is within the FieldOfView vertex. To prevent checking of all objects I made a matching mesh collision so that we could refine the scope of objects to check. When an object collides we then check if the object is within the FieldOfView vertex so we know that we can actually see it as well. For example a target around a corner would generate a collision but we would not be able to see it. So if these conditions where true we add the object to a Potential Targets Array which we then could use in our targeting system. The problem with this turned out to be the FieldOfView itself ! For example when we have a character that was bigger then our eye sight it would obscure our vision. Which of course is intended but also meant that when we checked of that character was in our FieldOfView we got irregular results as we could not see the objects front if we where behind him and vice versa.

The second iteration of the target system : Abandoning this tactic I went for a much simpler one where we now just shoot a RayCast line from the target to the source in our collision field. If the RayCast actually hits the target then obviously we can see him and add it to the potential target list. After this was done it was a simple matter of binding the Tab key to a script that cycled through all our potent targets in the array move a targeting ring underneath the selected target.

Β 

GUI Element for the selected target : Now that we have a target selected it would be nice to reflect that not only by using a targeting ring but also in the GUI. I wanted to create the classical item where you see a ring containing the animation of Β the head of your target, so you can see its facial expression when tossing that fireball at him ! Next to that the defaults like name and health bar. The name and health bar where pretty straight forward and nothing special. It took a bit more to get the characters head in there though πŸ™‚ After some research I found out that you could use a RenderTexture, which is a unity pro feature. This texture can display for example the image of a camera bound to it. So I set up a new dynamic camera that would attach itself right in front of the face of our selected character and send it’s feed to the render texture which is placed inside the GUI target ring. This worked as a charm but you would see everything behind the target as well. Setting the camera depth to a very small value made sure that everything behind the head turned into a solid color , which you could then make transparent. There you go, A live feed of your targets head in the GUI πŸ™‚

Β 

The new spell :

Images

Of course you cannot have a mage without the classic Magic Missle ! In stead of just creating a particle effect that zips in a beeline from caster to target I wanted it to be a bit more dynamic, chaotic and in the future make them more controlled. Now that we do have a targeting system we can select our target and prepare our missiles. The first step is getting a beeline from our caster to the target, get the distance between them and divide that by a reasonable amount so you get equal chunks. Then I wanted to deviate randomly some points off that path. Wes helped me with the 3d vertex math of placing the points randomly among the X and Z axis. After this was done I usedΒ iTween to give it the missle, the path and the final target. As each missile will calculate its own random path on instantiation you get a very nice chaotic effect when shooting for example a barrage of 5 magic missiles πŸ™‚

Β 

Fixing some of the animations : Currently when you are walking around and start casting a fireball the casting animation would take over from walking and you’d slide forward until you are done casting and the walking animation takes over again. This really looks nasty. In stead of needing an other animation that makes the character walk and cast unity allows you to actually combine the two separate animations ! First you have to put the animations into layers and group those on mutual exclusiveness. For example idle, walk , run will be layer 0 and casting in layer 1. Then you detect if you are moving and want to cast. If this is the case you’ll tell the casting animation that it may only use the animations from the spine of on. This way the legs are being left alone. Now you can blend the two animations creating a walking casting character !

Β 

Finally:

As I’m getting more and more to terms with unity and the scripting I wanted to clean up all of the scripts made before. Making sure to abide by the conventions of naming classes, variables and methods. Also the project’s hierarchy was becoming quite messy so we cleaned that up as well.

As usual you can find an updated progress of the current state here πŸ™‚

Another weekend, another Unity hackathon. One of the nice thingies I created today is a simple script that tells me what object my mouse is pointing at.
The source code for Physics.Raycast offers examples that help with mouse-to-screen conversion and ray casting, but they don’t wrap it up into a plug ‘n play script.
This one should be just that.

I wonder if this is the right way to handle this or if there is a built-in function to do it, which I overlooked.

I’ve also attached a screenshot and demo level I’ve dubbed Neon City. It uses self-illuminated cylinders with a black/white texture for the borders. There are stacks of boxes with a brushed steel texture that uses the Reflective/Parallax Diffuse shader for shininess and for a reflection of the sky texture. Either way, it was fun playing around with baking lightmaps and seeing what you can do with Beast. It’s really, really easy to setup a scene that seems to have small lights every everywhere, even though there is only a single Directional light in the entire scene.

Another fun thing Gerard and me discovered today is how easy it is to place a camera in the scene and have it render its output onto a plane somewhere else, to create a security camera + monitor system.

One thing that bugged me about earlier demos is that almost every edge in the game appeared jagged instead of being smoothed by anti-aliasing. In order to render real-time shadows from point lights such as fireballs, the rendering path needs to use Deferred Lighting. The trade-off, as documented on the Unity3D site, is that there is no anti-aliasing in Deferred Lighting mode. The default Forward Rendering mode gives you anti-aliasing, but no real-time shadows from Spot/Point lights. Only from one Directional light.

Unity is very helpful that it lets you know that only directional lights have shadows in forward rendering, but according to Warwick Allison, you can create your own shader with the fullforwardshadows setting to enable shadows on your surface. After an hour or so searching and surfing, I did not manage to find a package with shaders that add this behavior to the default shaders, so I guess I’m looking for something that either people don’t find too bothersome or that’s too hard to do. For now, I hope that a future version of Unity will fix this.

Anyway, here’s the source code for the detector script and below that is a screenshot of demo 7.


#pragma strict;

/***********************************************************************************************

Usage example:

  public var cam : Camera;
  public var text : GUIText;

  // If the mouse points at a an object, display the name of that object on screen.
  function Update () {
    var obj = MousePointerObjectDetector.Detect(cam);
    if (obj) {
      text.text = "Hit: " + obj.name;
    } else {
      text.text = "No hit";
    }
  }

***********************************************************************************************/

// For the camera, return the Transform of the object that is pointed at by the camera.
// Returns null if nothing is pointed at.
class MousePointerObjectDetector {
  public static function Detect(camera : Camera) {
    var pos : Vector3 = Input.mousePosition;
    var ray : Ray = camera.ScreenPointToRay (pos);
    var hit : RaycastHit;
    if (Physics.Raycast (ray.origin, ray.direction, hit)) {
        return hit.collider.transform;
    } else {
      return null;
    }
  }
}

Screenshot of demo 7

Teaser1

iTween is a very nice script that will help you animating your objects with a nice and consistent abstraction. Animation itself is not that hard in unity but why make your life harder then it already is ? The documentation of iTween is very clear and well written. Also it seems like everyone is actually using it πŸ™‚

Sometimes you need to take care when importing that you do not end up with a duplicate of iTween since they can cause conflicts. Just remove the one from the import so it uses your default version.

Analysis of a movement script

Last weekend I experimented with various aspects of Unity 3D to get a feel for it and to see if I would like to learn more. I was convinced after less than an hour, so now I want to learn more. First, I’ll try to get an intuitive understanding of the basics.

The Tornado Twins have an excellent series of YouTube videos where they build a simple game and explain basic concepts like movement, having turrets shoot bullets at you and more.

I watched the first 11 episodes yesterday evening and decided to see if I could build something similar with what I remember and by using the documentation.

Movement was the first thing I stumbled over. The concepts are clear to me, but the details of how to do it remain blurry. In the documentation, I found the example for CharacterController.Move().

At first the example looked overly complex to me, so I started taking out most of the code until the Update() function only contained three lines. And my sphere happily moved through the area. I was not happy with using the arrow keys to strafe to the sides, so I adjusted it to use up/down to move forward/backward and left/right to turn to the sides. I now had four lines.

While running/rolling/floating/whatever around with my sphere, I found myself tapping the space bar every couple of seconds because I wanted to jump, but the sphere stayed on the ground. It was time to add jumping back to the script.

So I started adding bits of code back in and before long I had most of the example code back, but jumping did not work yet. Fiddling around with the gravity manipulation eventually made me realize I needed to divide gravity by Time.deltaTime to reduce the per-frame effect of gravity instead of applying it about 200 times stronger than intended.

After this, my script was working and the sphere happily races around in its playground. However, it seemed useful to dive back into the code and extensively comment it for posting on our blog, to help me understand how it works. They say that the best way to learn… is to teach.

Enjoy the source code!

// This script moves and rotates the character controller using the arrow keys.
// Space can be used to jump.

// Variables available from the editor to tweak how fast the character moves
public var speed : float = 6.0;
public var gravity : float = 20.0;
public var jumpSpeed : float = 8.0;
public var rotationSpeed : float = 1.0;

// Movement vector. It's stored outside of the Update() function to
// remember the vector while jumping and increase the pull of gravity
// on the character over time.
private var moveDirection : Vector3 = Vector3.zero;

// The character controller that we're manipulating.
private var controller : CharacterController;

function Awake() {
  // Since we're not going to swap the CharacterController on a character,
  // we'll look it up once and store it in a variable.
  // In theory this should save a few nanoseconds every frame.
  controller = GetComponent(CharacterController);
}

// Update gets called every frame, so remember to multiply all numerical
// effects with Time.deltaTime to make them framerate-independent.
function Update() {

  // Rotate based on the left/right arrow. Since we spin around the Y-axis,
  // we only need to use the up direction of the Vector3.
  transform.Rotate(Vector3.up * Input.GetAxis("Horizontal") * rotationSpeed);

  // When on the ground, move. Otherwise, don't re-create a new moveDirection,
  // but let gravity do its thing on the old one to drag us back down.
  if(controller.isGrounded) {

    // First create a local space vector to describe our intended movement
    // and its speed.
    var localDirection = Vector3.forward * Input.GetAxis("Vertical") * speed;

    // Take the local movement and transform it to world space, this is because
    // CharacterControler.Move wants a movement in world space.
    moveDirection = transform.TransformDirection(localDirection);

    // Force our upward momentup to jumpSpeed when we press space.
    if(Input.GetButton("Jump")) {
      moveDirection.y = jumpSpeed;
    }
  }

  // Apply gravity to the current moveDirection object, no matter if we decide
  // to move or not. Gravity is modified by Time.deltaTime to smooth it out over
  // time. Note that it's outside the if block and thus also triggers in the
  // air.
  // This is why jumps are so smooth: we have an upward momentum from the
  // jump and now we are reducing the positive momentup each frame until it's
  // zero (at the top of the jump) and then each frame the character is
  // pulled down faster because the momentum becomes more negative.
  // When we hit the ground, the block above kicks in to reset momentup to zero.
  moveDirection.y -= gravity * Time.deltaTime;

  // Actually perform the move. Note that this is modified by Time.deltaTime to
  // make it framerate-independent.
  controller.Move(moveDirection * Time.deltaTime);
}

// Ensure we have a CharacterController component included in our character.
@script RequireComponent(CharacterController)


Screenshot of demo 6
Demo 6

Mixamo

Because we come to game development from a background of programming, creating 3D models is not something we’ll likely do ourselves. In our search for a good source of 3D models, we found Mixamo. Mixamo is awesome!

Mixamo does three things:

  • They sell 3D models
  • They sell animations for 3D models that ‘just work’ with their own models
  • They offer a service that allows you to animate any 3D model you upload, as long as it has the minimum number of bones in it to perform the animation

They have a couple of freebies in the Unity store, but most of their model packs cost about 40 dollars. Separate motions usually go for 10-20 dollars. Custom motions and sequences of motions get more expensive as you increase their complexity.

My plan for this second weekend on exploration in Unity3d : Give’m goblins some behavior !

Last weekend I basically had a plane with some Goblins standing statically around doing their best imitation of a sitting duck and looking funny at you. As a player we could could walk around and toss fireballs at them. But hey that’s not much of a challenge now is it ?

Time to add some life to them. The first thing I wanted to give the Goblins was some way of moving around. It would be nice if they could wander around and even better, to walk a patrol route ! So after messing around with some animation code, dumping some gameObjects as patrol nodes, etc, they where able to walk a patrol…..as long as nothing was in their way ! I would need to give them a sense of their surrounding to get around obstacles between their path. Pathfinding it is then.

In the asset store I found exactly what I was looking for : Simple Path by Alex Kring. After watching the video and reading the documentation I started with the implementation of it. This could not be simpler ! In no time I had my Goblins wandering around and patrolling all over the place πŸ™‚ In the demo’s that came with the plugin i found that you could even let objects chase an other one. Perfect !

Looking at the scene now shows a bit more life. Though the goblins now are horrible failing at playing sitting ducks, we as a player have a bit of a harder time to shoot them down with our fireballs πŸ™‚

Next up :

Give the patrolling and wandering goblins something to look for, obviously the Player for now. I looked for a Field of View tool in the Asset Store and … was pleasantly surprised with : Fov Mesh Maker by Hyungseok Seo. The documentation is quite hard to read, but the author did his utmost best to write it in English. The examples provided with the plugin are quite well and gives you all the information that you need to work with it.

After messing around a bit we now have some goblins with vision ! I guess before they had some freaky third eye or where psychic. Either way, now they can actually see where they are going πŸ™‚

By now the scene evolved to a bunch of goblins that are roaming around, patrolling and looking for the Player. If they spot the player, they start casing him for ever and ever more.

Evolve the scene and add some gameplay !

I tried to make the scene a bit more interesting by adding a room in the middle of it. Due to the placement of the room we have an outer ring that we will now call “corridor”. The room has one entrance and in the room I put a cylinder with a glowing golden ball. This is what the goblins will try to protect.

With these elements in place we can now work on more behavior code : The player has to avoid detection by the patrolling goblin in the corridor. sneak into the room and get to the golden ball without being detected. If one of the goblins in the room spots the player, he should run for the alarm gong and rouse all other guards in the room so they can join him in chasing the player.

Building the Alert mechanism was quite fun indeed πŸ™‚ On google i searched for a free 3d model of a chinese gong that could function as a nice prob. After a bit of searching around I found a really nice 3d studio model. Upon importing the model my scene grinded to a halt. The model has _so many_ polygons that basically the GPU turned nuclear πŸ™‚ I either had to look for a low polygon one or somehow fix this one. Searching google for this problem i found a solution \o/

I should be reducing the amount of polygons the object. To accomplish this I used MeshLab. Now the model was nice at 7500 tris ! Awesome stuff we have an alert gong prob standing ready for a goblin to bang his head against , or _if_ its smart enough he’ll use one of his brethren as a battle ram πŸ˜€

Binding the guards to the alert Gong should help us in the level building. Basically you would like to just drop in the alert gong and your prefab guards should be automatically registered. To accomplish this I added a boolean to the goblin prefabs isGuard. The gong would have a big collision box on it that is setup to act as a trigger. Now make the box as big as the area you want to alert gong to cover. Any guard in the collission box will be registered by the alarm. When a guard sees the player he will make a run for the gong and sound the alarm ! The alarm prob monitors if it is sounding and if so it will send a message to all the registered guards to start chasing the player.

With all this in place we had some basic gameplay mechanics and the clock stroke 01:00 sunday night…. Quite happy with the progress i could finally head to bed and have some well deserved sleep , finally ! (i can never sleep well when working on stuff so friday and saterday night the sleep did not come…)

You can View the progress of last weekend just to get an idea of the state i was at before i stared to continue this weekend.

And here you can view the results of this weekend !

(use 1 to shoot a fireball !)

MeshLab

MeshLab is an is an open source, portable, and extensible system for the processing and editing of unstructured 3D triangular meshes. And can be found on source forge.

The nice thing about this tool is that it allows you to import an 3d model in about any format. Once imported you can optimize the model by reducing the amount of polygons.

Take a look at this video to get an impression of how awesome this tool is :

http://www.youtube.com/watch?v=w_r-cT2jngk

Fov Mesh Maker by Hyungseok Seo is a very nice tool if you would like to know if objects are in a field of view of an other object.

I’ll let the video do the explaining :

Design a site like this with WordPress.com
Get started