Archive for the ‘C#’ Category

The Way Things Used To Be :: Reset Components and Unity 3D

One of the very interesting aspects of Unity 3D and its architecture is the fact that it is component based. This one factor makes it very easy to implement some very interesting behavior in your games that separates concerns rather nicely. One such interesting notion is that of a Reset component.

When the Horseman created Hug Monster he realized quickly that he’d need to store the initial positions of the game’s objects somehow. Re-loading the Scene every time the player dies is simply unacceptable given the time Unity takes to perform loads, so somehow there must be a way to easily store initialization data. In other langauges such as AS3 the most tempting way to do this would be to implement something like :

HugMonsterGameObject
  public function getInitialValuesFromScene():void{ /*collect initial values*/ }
  public function reset():void{ /*reset to initial values*/ }

As a consequence, all game objects would carry this baggage around, and they all must remember to subclass HugMonsterGameObject whether they needed the functionality or not. This doesn’t sound bad on its face, but it can bloat the number of responsibilities of a given class, such that it simply has to concern itself with “too much.” On the bright side, Unity’s component-based architecture allows us to split this behavior out completely! I do have a Player class, and a Hugmonster class, but neither of them knows a thing about how to grab initial coordinates or restore to an “initial” state. Instead, the gameObjects that have Player and Hugmonster components (as well as everything that can be moved or altered) have a ResetBehaviour object sitting alongside their “main” component.

How it works is as such.

// In the file ResetBehaviour.cs
//    This is merely an abstract class, to give 
//    us a typed Component that is responsible 
//    for Resetting things.
 
using UnityEngine;
using System.Collections;
 
public class ResetBehaviour : MonoBehaviour {	
	virtual public void RecordStartingVariables(){}	
	virtual public void ResetGO(){}
}
 
 
// In the file GenericResetBehaviour.cs
//    Our most basic implementation of ResetBehaviour.
//    This is ideal for things like the blocks that 
//    the Hug Monster can shove around, or for
//    other miscelaneous objects that only move 
//    with position / rotation and have a 
//    changing velocity.
 
using UnityEngine;
using System.Collections;
 
public class GenericResetBehaviour : ResetBehaviour {
 
	public Vector3 resetToPosition;
	public Quaternion resetToRotation;
	public Vector3 resetRigidBodyToVelocity;
	public Vector3 resetAngularVelocity;
 
	// Use this for initialization
	void Start () {
                // Unity's default Start method
                // is an ideal spot to initialize
                // since this is where the object
                // was placed in the editor.
		RecordStartingVariables();
	}
 
	override public void RecordStartingVariables(){
		resetToPosition = transform.position;
		resetToRotation = transform.rotation;
		if(rigidbody != null){
			resetRigidBodyToVelocity = rigidbody.velocity;
			resetAngularVelocity = rigidbody.angularVelocity;
		}
	}
 
	override public void ResetGO(){
		Debug.Log("Default ResetBehavoiur");
		transform.position = resetToPosition;
		transform.rotation = resetToRotation;
		if(rigidbody){
			rigidbody.velocity = resetRigidBodyToVelocity;
			rigidbody.angularVelocity = resetAngularVelocity;
		}
	}
}

If an object needs a more specialized form of ResetBehaviour, I can simply derive from GenericResetBehaviour without necessarily overriding anything in the Player, Hugmonster, Switch, Wall, Camera, or any other class definition. This makes content creation and behavioral scripting ridiculously flexible.

But Mr. Horseman, why make Reset components for all these objects? Don’t you have to then grab that component from each game object, by specific type, and call ResetGO() on it?

Aaaah, I’m glad you asked. You do NOT have to do any such thing! The reset level code, which lives inside the GameManager class looks something like this…

public void RestartLevel(){
 
		ResetBehaviour[] rbs = Component.FindObjectsOfType(typeof(ResetBehaviour)) as ResetBehaviour[];
		foreach(ResetBehaviour rb in rbs){
			rb.ResetGO();
		}
 
                // a few more lines of code for displaying the Game Over text go here.
}

Because the ResetBehaviour class is virtual, and because all the Reset components derive from it in some manner, all I have to do is find every component derived from ResetBehaviour using the handy function shown above and then iterate through the resulting array an call ResetGO() on each. Every item in the scene will reset to its initial position as specified by the component without any further work on the developer’s part.

I have to say that I first looked at the component system and saw the potential for chaos, but in fact the philosophy underpinning the Unity Editor gives you ways to funnel that chaos into pure elegance.

Tags: , , , ,

5 Comments


I dare you! I Ludum Dare you!

The Horseman recently gave a presentation on the 2DToolKit sprite animation library and toolchain at his local Unity 3D Users Group. As it happens, one of the attendees asked The Horseman if he’d ever heard of Ludum Dare and its 48 hour game competition. I had to admit that I was not familiar with it, which might be somewhat surprising given its connection to Minecraft. However, upon reading about what Ludum Dare is and upon hearing that the next competition was starting the very next night, The Horseman did a quick check on his calender to make sure he wasn’t about to blow off any engagements and then declared his intention to enter the competition. It was high time to determine whether he could create a game from the ground up using Unity 3D and the 2D Toolkit in 48 hours. What follows is a summary of the experience.


(The tl;dr version : “Yes, The Horseman can do such a thing and the resulting entry is here under the name dr_soda. There also exists a post-competition build with some improved jumping controls, new levels, and new features that is playable at www.hug-monster.com.)

- Ideation -

When you have 48 hours to create a game you don’t have a lot of time to waste coming up with the perfect idea. Coming into the competition completely blind, I did not have any idea what the theme could be (and indeed nobody really knew what it would be until it was announced) so I did not prepare in any way for what might come. As it turns out the theme for this competition was simply Alone. That was my sole guidance for the direction of the resulting game. After about an hour spent thinking of ideas that were at best “maybe” in terms of fun and at worst “too ambitious” in terms of scope, I came across the idea of the player wishing to be left alone by a lovable, excitable, and adorable emoticon named “Hug Monster” and rendered as such : (-o^_^)-o. Considering this to be both the most interesting take on the theme, and also the most achievable concept in the remaining 47 hours, I sat down to refine the elevator pitch version of the game.

The Hug-Monster (-o^_^)-o can never get enough love or hugs, and is always happy to see you. Unfortunately, it’s a little too excitable and at times doesn’t seem to know its own strength.

You on the other hand are small and fragile, and most definitely want nothing more than to be left alone, especially from the big, scary Hug-monster!

How long can you avoid its warm, snuggly, and loving arms of death? Find out in this classic platformer!

- Artistry -

Since I wanted to keep the mood of the game upbeat in the face of the otherwise bleak theme of “Alone” I decided to make the graphics consist of cute emoticons that would be relatively easy to animate with 3 – 5 frame walk cycles. The Hugmonster flails its arms joyfully as it slides across the stage in perpetual persuit of the player. The player itself is merely a “letter” from the Wingdings font set, the skull and crossbones, rendered at 12px size such that it looks more like a little man than what it actually is. Both of these concepts took very little time to render once I’d settled on the proper font sets on which to base them. Once I had my sprite sheets, it was a quick trip into Unity3D and the 2DToolKit and I had (almost) all the sprite animations I would need. Later, once I decided that the levels needed more interactivity, I went back to Photoshop to create a set of switches, again using glyphs from the standard font set available with any Photoshop install.

- Development -

Being no stranger to side-scrolling mechanics from years of writing ActionScript for Flash games, and even a few little experiments on the subject in C# for Unity in the month prior, writing my own implementation of the walk/run mechanics was no large task. I decided that I would let Unity handle the physics for me this time, rather than write my own physics engine. I’d learned some valuable lessons on what works and what really doesn’t work when using Unity’s physics and felt confident that I could get what I wanted out of it. Rather than use Unity’s built-in CharacterController module, I chose to write my own Ambulator class with its own movement logic and use that for both the player and the Hug Monster. Partly this was because I’d forgotten that CharacterController exists, but also even if I’d remembered I may still have opted to create my own Ambulator simply because I wanted to minimize the amount of Unity-isms that I’d have to remember how to work with, and I already know very well how to write the kind of code I was aiming for without relying on Unity’s help to do it.

It turns out that this combination of decisions was simultaneously the best choice I could make and the worst choice. I liked (and still like) the simplicity of the Ambulator, and I feel it does exactly what it needs to with no overhead or extra API functionality to worry about. Then by letting Unity handle the physics of falling objects, there was a whole class of code I did not have to write in order to make the characters collide which saved valuable time. On the other hand, there are many idioms for working with the physics engine in Unity that aren’t always the most conducive to the traditional 2D platformer physics that players expect, and this expressed itself in how the character handles jumping face-first into a wall or obstruction. The difficulties can be worked around, and to a large degree I did manage to work around them (though not to the degree I wanted to by the end of the 48 hours), and after the end of the competition I have discovered yet more ways to work around them. I think this was possibly one of the most valuable technical lessons I took away from the experience of making a Ludum Dare game. If I were to do it again, I would probably choose to implement more of the physics on my own rather than to use the CharacterController component, but I think there’s a good case to be made for trying both approaches just to see where the limits are.

- Sound Design -

You’ll notice that there are no sounds or music. I’ll come out and say it, my history has not included much in the way of sound design. That isn’t to say I didn’t give it a shot, however. I followed the advice of fellow Ludum Dare entrants and traveled on over to BFXR to see if I could cobble together some nice sound effects, and maybe even the rudimentary beginnings of a music loop. After 3 hours of fiddling around with settings and sound generation I realized that I was getting nowhere. Nothing really sounded like I wanted it to and I was beginning to feel that I wouldn’t have the time to really test out every combination of sounds such that I would know how to achieve the effect I was after. This being the case, I chalk it up to a lesson learned even though it ultimately did not advance the state of the final build. I won’t make that mistake again. By the next Ludum Dare I will either know enough to make my own sounds to my satisfaction or I won’t even make the effort and save the time for design or programming. Speaking of design…

- Level Design -

A consequence of my decision to make a game in which a little person flees from the loving embrace of an oversized monster is that level design is critical in selling the idea, because what you are creating amounts to an action-puzzle game. As you might expect then, all the time that was not spent generating art, music, programming, or concepts, was spent designing levels. By the time the competition ended, I had created seven of them. They all had been tested to make sure they were beatable, but also that they could not be cheated. This took time… lots of it. Inherent in creating all these levels was also the playtesting of them all. Any time I wanted to add a switch, a door, move the goal, move a platform, I had to test the entire level from the beginning. As such the levels are short. What they lack in length though, they tend to make up for in difficulty. I’m still finding the appropriate balance here. I think I could have done a better job easing the player into the rules and logic of the game world rather than throw them to the wolves immediately.

- Flair -

You can’t have a game without a title screen or an ending, right? Well, this game had to have both. The most fun part about this was the the title screen and the ending movie both are programmatically animated using the same logic that the characters use in the game. They appear to be acting “intelligently” but in reality are simply doing nothing more than following the logical results of the input supplied as though they were doing their normal business. Astonishingly, I feel like this was possibly the most fun part of the process for me : taking the engine and assets I’d built for use in a game and re-purposing it all to make a set of little movies.

- In Conclusion -

The competition was easily one of the most fun and rewarding weekends The Horseman has spent in the past year. Creating a game under such tight constraints was exhilarating and the knowledge that there were hundreds of other people attempting the same thing was incredibly motivating. When taking breaks from the action, The Horseman would look back at the Ludum Dare blogs to see how other people were progressing, and take heart at the progress of others and admiration at their interpretations of the theme. Would he do it again? The Horseman says : “Verily.”

As well, he says : Play Hug Monster! (-o^_^)-o

Tags: , , , ,

6 Comments


Further extending the Unity 3D editor

In our last entry, The Horseman revealed to you an incantation to transmute Unity’s Editor itself. That entry merely skims the surface of what a practitioner of the arts may accomplish through Unity’s editor scripting capabilities. In today’s lesson, we build on top of the previous layers of sorcery such that we can overcome a pernicious problem with getters and setters in C# scripts. As before, project source for this tutorial is available.

Those of you who have spent even a small amount of time adding scripts to Unity’s GameObjects stand a fair chance of having encountered a magnificent property of the editor. A public instance variable declared as a member of a class will be exposed in the inspector for that game object, so if we were to give the PunyPlane a property called health, that property would be editable within the editor on an instance-level basis.

public float health = 1000;

Yes, I hear your questions even before you ask: “But Mr. Horseman, what about encapsulation? What if I want to hide health behind a getter / setter pair? It would be great if the PunyPlane could notify listeners of a change in health, or possibly even alter its own size such that it shrinks as its health decreases.”

Well, let’s try it out!

	protected float healthMax = 1000;
	protected float health = 1000;
 
	public float HealthMax{
		get{return healthMax;}
		set{healthMax = value;}
	}
 
	public float Health{
		get{return health;}
		set{
			health = value;
			ResizeBasedOnHealth();
		}
	}
 
 
	protected void ResizeBasedOnHealth(){
		// As health approaches 0, scale should approach 0.5, 
		// to make the object appear half its normal size
		// when health is depleted.
 
		float newScale = 0.5f;
 
		if(health > 0){
			newScale += (health / healthMax) * 0.5f;
		}
 
		gameObject.transform.localScale = new Vector3(newScale,newScale,newScale);
	}

Huh.

It appears that you can’t encapsulate a variable if you want it to be editable in the Unity Editor. Of course, looks can be deceiving and two can play at deception in this grand illusion. There are in fact several ways to get past this difficulty, and the one you choose depends on what’s most important for your purposes.

The most simple of these solutions is to set up your function to implement the PunyPlane.OnDrawGizmosSelected function, which is called approximately once every 10ms while an object is selected in the Editor.

 
// leave health exposed as public...
public float health = 1000;
 
void OnDrawGizmosSelected() {
     // and when in Editor mode, call ResizeBasedOnHealth on every update
     if(Application.isPlaying == false){
         ResizeBasedOnHealth();
     }
}

This simple solution allows GameObjects to call functions that act on the publicly exposed values in your game. Here, you can set the health of any PunyPlane in the editor and watch as its scale changes on the fly while you edit the Health field.

But Mr. Horseman, what if I want ResizeBasedOnHealth to be called at runtime whenever health is changed? This only works in the editor!

It is at this point that we dig a bit deeper, and uncover the Editor class. You will create a new C# script located in “Assets/Editor” and rename it as PunyPlaneEditor. We’ll start off with this code inside:

using UnityEngine;
using UnityEditor;
using System.Collections;
 
// Remember to declare the Type of editor this should be!
[CustomEditor (typeof(PunyPlane))]
public class PunyPlaneEditor : Editor {
 
	/* * 
	 * This function is called repeatedly as the Inspector GUI is refreshed.
	 * */	
	public override void OnInspectorGUI(){
 
		// Our "target" is the particular PunyPlane
		// instance that is currently selected, and
		// whose properties this inspector panel
		// reveals.
		PunyPlane pp = target as PunyPlane;
 
		GUILayout.Label("PunyPlane Custom Controls");
		pp.Health = EditorGUILayout.FloatField("Health",pp.Health);
 
	}	
 
}

Now, young seeker of arcane wisdom, behold what you should see :

Our custom Editor script has usurped control over Unity’s default implementation and displays for us a field containing a floating point value that we have labeled “Health”, which gets and sets from PunyPlane.Health, the getter / setter pair. The drawback to this method is that it takes work to make your custom inspector layouts look aesthetically pleasing, and if you have a large number of editable fields this can become an onerous task. This should only be undertaken in the event that you have a side effect that must be triggered both at runtime and in the editor, and you don’t want to incur the overhead of performing the operation in the normal void Update() method belonging to all MonoBehaviour objects. The other limitation of the OnInspectorGUI method is that Screen.width and Screen.height will return the pixel dimensions of the inspector panel, not the game screen or the scene. If you need the pixel dimensions of the Scene editor, you can instead perform those actions in Editor.OnSceneGUI() and also from within the OnShowGizmosSelected handler. On the other hand, if you need the precise pixel dimensions of the Game window those are not available at all from within the editor scripts… but there is a way yet to reach them, in the event that you need those dimensions at runtime and you cannot, or do not wish to hard code them. I’ll save that bit of prestidigitation for another time.

There are yet other ways to interact with and change the Editor’s behavior. Virtually anything you see happen in the editor can be harnessed for your own purposes.

Download the source for this tutorial.

Tags: , ,

No Comments