2013/12/10

Grid Framework version 1.3.5 released

Grid Framework version 1.3.5 has been approved last week, here is the changelog:

  • Added a new event for when the grid changes in such a way that if would need to be redrawn.
  • Some of the exmples were broken when Unity updated to version 4.3, now they should be working again.
  • Overhauled the undo system for the grid align panel to remove the now obsolete Unity undo methods.

I promised I would be working on Playmaker support, so what's going on here? I have been bogged down a lot with studies and real life stuff oder the last months (nothing bad though, don't worry), so things were going slowly, but they were moving. The current problem is Playmaker itself; from what I have used it is a fantastic system to crate game logic and totally worth it, however, when it comes to extending it things aren't that nice anymore.

I am in contact with a staff member who is helping me out, so I'm not entirely reliant on the lackluster documentation, but there is a lot of ugly code redundancy that cannot be avoided. I'm still working on it and it will come out eventually, but it will take more time. How much? I don't really know, it depends on how rigid or flexible Playmaker turns out to be.

2013/09/20

Grid Framework version 1.3.4 released

This is a small update, it adds the ability to offset the origin of the grid. It also adds a chapter to the manual about extending Grid Framework with your own code. There is nothing in there experienced .NET user wouldn't know, but I figure some user might not know about extension methods and might do things in a hacky way, so I added the chapter to it, along with example code.

2013/08/21

Grid Framework version 1.3.3 released

Grid Framework version 1.3.3 has been approved by the Asset Store team. This update adresses a bug introduced in version 1.3.2 where values of colour vectors (such as axisColor) and bool vectors were not persistent. Now they will stick again. I also broke the examples for the sliding puzzle and movement with obstacles, which are now fixed. Based upon a customer's question I also built a snake game example; it's mostly an extension of the grid-based movement but with several snake segments following each other.
And last, but for some people certainly not least, if you delete the local documentation (found in the WebPlayerTemplates folder) the help menu entry will forward you to an online documentation instead. Some customers complained about me cluttering their project with that folders, and they are right, but unfortunately that's the only place where I can place the files, or else Unity will try to compile the JavaScript files and throw a ton of errors.

The documentation files are all contained in that one folder, so you can either uncheck it when importing, delete the folder after import or move it somewhere else. I know this is inconvenient, but unless Unity provides me with a proper way to bundle offline documentation this is the best I can do.

2013/08/09

Grid Framework version 1.3.2 released

Version 1.3.2 of Grid Framework has been approved by the Asset Store Team. The biggest news is the  addition of new coordinate systems for hexagonal grids. You have cubic coordinates, rhombic coordinates and the old odd herringbone coordinates now. Even herringbone and barycentric coordinates will be added at some point in the future for the sake of completion, but they are no priority.

The documentation received a complete overhaul. Rather than two manually typed PDFs you now have one automatically generated Doxygen documentation in HTML format. Previously you accessed it by double-clicking the PDF in your project view, not you can just go to Unity's help menu and the documentation will open up in your browser.
The user manual and scripting API are now together again. The top- and sidebar of the HTML can be used to quickly find what you want. There is also a new section called Legacy Support that contains information on changed or dropped features and how to restore them or upgrade your code. The changelog has also been added to the manual, thanks to Markdown you now have both a nicely formatted HTMl and a well readable plain text file.

There are also two new examles. The first example constructs a SimCity-like terrain mesh from a plain text file containing the heights as integers and allows you raise and lower vertices by clicking them. Just set up your grid, insert your height file and click play.
The other example uses polar grids to simulate a rotary dial, as found on old telephones. Click a number and the dial will rotate that much, print a message and then rotate back. This example can be used for circular GUIs, menus, clocks or anything else that needs to rotate around angles.

There is also the usual bug-fixing, vertex matrix methods got cut and the NearestFace/BoxG methods of rectangular grids have changed somewhat. You can find the exact details in the Legacy Support section of the documentation. Here is the full changelog:

- Hex Grids: new coordinate systems, see the manual page about @ref hex_grid for more information.
- New HTML documentation generated with Doxygen replaces the old one.
- Fixed a bug in `Angle2Rotation` when the grid's rotation was not a multiple of 90°.
- _New example:_ generate a terrain mesh similar to old games like SimCity from a plain text file and have it align to a grid.
- _New example:_ a rotary phone dial that rotates depending on which number was clicked and reports that number back. A great template for disc-shaped GUIs.
Some existing methods have changed in this release, please consult the @ref legacy_support page of the user manual.
- Rect Grids: changed the way `NearestBoxG` works, now there is no offset anymore, it returns the actual grid coordinates of the box. Just add `0.5 * Vector.one` to the result in your old methods.
- Rect Grids: changed the way `NearestFaceG` works, just like above. Add `0.5 * Vector3.one - 0.5 * i` to the result in your old methods (where `i` is the index of the plane you used).
- Hex grids: Just like above, nearest vertices of hex grids return their true coordinates for whatever coordinate system you choose.
I am sorry for these changes so late , but I realize this differentiation made things more complicated in the end than they should have been. It's better to have one unified coordinate system instead. Read the @ref legacy_support to learn how to get the old behaviour back.

2013/08/02

Status update and Doxygen rant

It has been two weeks snce my last update, so I wanted to let you guys know what I am currently at. The good news is that the new coordinate systems have been implemented and are ready to use. Of course there is still the obligatory last check to do, but i expect everything to be fine. All methods that got the axe are now gone as well and have been put into extension methods and ZIPped into archives; that way no one will accidently use the deprecated API. I also added a section called Legacy Support to the manual with instructions.

Now for the promised rant. I have transitioned all the documentation to Doxygen, both scripting reference and user manual. Now all that would be left would be to sprinkle some CSS fairy dust on top of it so it looks nice and I'm done. Except editing the CSS is an exercise in pure trial & error frustration, there is no documentation for it and the code is barely commented. The manual is a pain in the butt as well, it's like it was written for people who already know how to use Doxygen. It will go into detail about all the possible ways of formating my text, but it doesn't explain how to get the text into the manual in a specific order. Don't worry, I got it all covered now, but it was not a fun journey.

I wanted to slim down the default HTML design, because I think the large header buttons at the top are too large and vibrant, but I've had it with Doxygen. Don't get me wrong, it's a great system and I'm sure everything made perfect sense when wrting it, but it is obscure from the outside. Anyway, I'm going to stick with the default design for now, but at least I limited the size of images so they don't disrupt the flow of the text. There probably won't be any PDF documentation anymore though, the HTML is more flexible to read and navigate, plus the PDF generated by Doxygen looks rather... ugly.

Now that I've got everything out of the way it's time to wrap it up and hopefully get it released next week.

2013/07/19

What's up next?

Hello everyone, I decided to do a status update so you know what's going on and coming next.

Two new examples

The first example is something I wanted to do for quite a while, it generates a terrain mesh like the terrain in games like SimCity from a plain text file. You provide the numbers for the height of vertices and the mesh gets created. On top of that you can click a vertex to raise it and right-click to lower. All the vertices will be placed along the vertices of the grid, so the level designer doesn't have to wory about the layout of the scene.
The other example is a rotary phone dial using polar grids, it's based on a suggestion by a customer (I always appreciate input, don't be shy ^^). You have a rotary dial, you click it and then it rotates like a real dial, depending on which number you clicked. It may no look very impressive on its own, but the template could be used for all kinds of cool UI displays and menus. It works by checking which sector of the grid was clicked and then multiplying that with the angle of the grid and then applying the rotation over time.
Both examples are already done and will definitely be part of the next update.

New hexagonal coordinate systems

This is the main feature of the upcoming update. Up until now the only coordinate system hex grids had was the herringbone pattern. It's easy to understand, but when writing for it you often have to differentiate between odd and even X-coordinate, which is... stupid. The new coordinate systems don't have that problem, but they are harder to understand, so pick your poison ;)
The first coordinate system is "rhombic", meaning the X-axis is rotated 30° upwards. This removes the need for the even/odd cases, but now moving south-west is actually moving west. The second coordinate system is "cubic", it uses three axes in two dimensions. To understand it remember the game Qbert, the game world is in 3D with cubes, but the actual graphics are in 2D and the cubes are actually hexagons. Finally, we have barycentric coordinates for the more mathematically inclined.
I really want this feature to be done before going after playmaker support. I know you guys want Playmaker and I keep telling you "later", but this is more urgent. The good news is that these coordiante systems turned out to be much less painful to implement than I originally expected. I still need to give everything the final polish and make sure the systems are not only mathematically correct, but also make sense to a human being, so I'm about 90% done.

New documentation with doxygen

Up until now I have been writing the documentation in Pages and exporting it as PDF. It was an OK workflow and the results looked reasonably well, but as Grid Framework's API grew it became more and more of a pain to write the actual documentation with all the cross-references and unified layout and styles. I have now reached the point where it would be just madness to continue, so I decided to switch to Doxygen. When you use Doxygen you comment your source code in a specific manner, then Doxygen parses it and uses your comments to document all the methods for a human to read.
The transition phase is ugly, I need to copy-paste or rewrite all my documentation, but once it's done any future updates will be much easier. This also means you will get documentation in both HTML and PDF format from now on.

Vertex matrix gets the axe

Finally, some not-so-good news. I have been thinking about this for a while, and the vertex matrix methods were never really good. The idea was to give you a quick and simple way to store some vertices of a grid in an array and be able to read them, but the way I did it is way too specific. It will only be useful in a handful of cases. This leaves me with two options: either expand on it, writing many variants of the method and on top of that doing the same thing for faces, boxes and edges, or just cut it out.
I decided to cut it out, because there is no point in dragging all that code along, when most people will never use it and some will only use a fraction of it. It would be much easier and better if the users themselves wrote their own methods, it's less than ten lines of code anyway and you get full control over what you want. You don't have to drag along an array that's four times larger than you need. When looking at the examples I wrote, not even I used the vertex matrix methods once, because it was easier and cleaner just to roll it from scratch.
Naturally this raises another concern, what about the people who were using this method? I can't just rip it out and tell them to write it themselves. This is where extension methods come into play: After I removed the methods I put them back into and extension method in a separate file, which I ZIPed. If you need the vertex matrix methods back just unzip it and you won't notice any difference. Of course if enough people actually want the vertex matrix to stay in place I'll put it back, but if no one objects this will be the way to go.

2013/07/03

CheckComponent()

Here is a quick but handy tip. Recently I found myself needing to reference various components in my script without knowing if they exist. I have to get the component and then check if it exists, and if not add it to prevent null exceptions. Here is what you would write in such a case:

MeshCollider mc = GetComponent<MeshCollider>();
if (!mc)
 mc = gameObject.AddComponent<MeshCollider>();
}

First we get the component and store it in a variable, then if it is null we add the component to the object. Simple, right? True, but if you need to do this several times it can get messy. You can copy-paste it once with a different type, but it gets tedious.

Fortunately we can call generics to the rescue! Let's wrap it all up into one generic function that works on any component:

private T CheckComponent<T>() where T: Component {
 T component = GetComponent<T>();
 if (!component)
  component = gameObject.AddComponent<T>();
 return component;
}

MeshCollider mc = CheckComponent<MeshCollider>();
Note that it is important for the type T to inherit from Component or else the methods GetComponent and AddComponent don't make any sense and will throw errors. We can take this even one step further by making CheckCompnent an extension method:
using UnityEngine;
using System.Collections;

public static class ComponentExtensions {
 public static T CheckComponent<T>(this Component theComponent) where T: Component {
  T component = theComponent.GetComponent<T>();
  if (!component)
   component = theComponent.gameObject.AddComponent<T>();
  return component;
 }
}

Now you can call CheckComponent as if it were a part of Unity's standard API, just like GetComponent.

// use this in any of your scripts:
MeshCollider mc = CheckComponent<MeshCollider>();

2013/06/17

Grid Framework version 1.3.0 released

Grid Framework version 1.3.0 has been approved by the Asset Store team. The biggest features of this release is the addition of polar grids. Check out the updated included examples to see them right in action. Notice how in the lights-out example the coordinates wrap around, maning that once you've exceeded the maximum angle it start from the beginning again without you having to worry about anything.
Even if you prefer the good old rectangular- and hex grids you'll want to take a look at the updated API: You can now get the direction vectors for up, forwarad and right or north, north-east, east, south-east and so on just by calling one command. This will make grid-based movement much easier, since you don't have to convert back and forth between grid- and world space anymore.
On top of that the lights-out and the runtime snapping example showcase how to dynamially generate meshes from grids. The tiles of the polar lights game are all individual meshes that fit exactly inside the idividual faces. When the game starts the attached script runs a loop that runs through the grid and creates the needed vertices and triangles and then assigns the proper materials.

Here is the full changelog:


  • added up, right and forward members to rectangular grids
  • added sides, width and height members to hex grids
  • added the enum GFAngleMode {radians, degree} to specify an angle type; currently only used in methods of polar grids
  • added the enum HexDirection for cardinal directions (north, north-east, east, ...) in hex grids
  • added the GetDirection method to hex grids to convert a cardinal direction to a world space direction vector
  • hex grids and polar grids now both inherit from GFLayeredGrid, which in return inherits from GFGrid
  • the Lights Off example now features a polar grid as well
  • procedural mesh generation for grid faces in the Lights Off example
  • mouse handling in runtime snapping example changed because it was confusing a lot of users who just copy-pasted the code
Please note that this version officially requires Unity 4, since that is what I was building with, but there is no new API used and the scripts will run just fine in Unity 3.

2013/06/12

Version 1.3.0 submitted

A quick heads-up, version 1.3.0 has finally been submitted to the Asset Store. Remember, the price will go up to 25$, so if you still want it for 20$ now is the time to buy.

2013/06/09

Feature freeze for polar grids

Here is a quick update: I have reached feature freeze for polar grids, meaning I'm done with all the features. Now I need some last polish and I must prepare new images for the Asset Store, then it's all good to go. So, what took me so long? Well, designing and writing code is one thing, then you have to put it to use This often reveals weak points, some things might seems counter-intuitive, or some things are more complicated to use than others.

One example would be making an object rotate as it moves through the grid so it's always facing outwards. Sure, you can do it using the existing API to convert through coordiante systems, extract the angle of the object relative to the grid's Z-axis and then use Unity's built in math functions to create the quaternion by rotating x degrees around the grid's Z-axis. That doesn't sound pleasant at all. That's why now you can just call the World2Rotation method to get the quaternion directly, then you can do whatever you want with it.

This delayed the release a bit but such small additions can make a big difference in the end. Another thing worth noting is that this release has been written in Unity 4 and as such it will list Unity 4 as the required version in the Asset Store. Unity 4 has been out for half a year now, but even if you still want to stick with Unity 3 you shouldn't have any problems as I didn't use any Unity 4 exclusive API.

Well, that's it for now, thanks for reading.

2013/05/26

Polar grid drawing refined

Hello again

Last time I showed a preview of polar grids it was a full cycle starting from the origin containing all layers up to the edge. During runtime if only part of the grid is visible to the player rendering the whole thing can be a waste of resources, that's why you have the option of specifying a specific rendering range.

I was trying out several approaches of interpreting the rectangular range, but in the end I went for a polar approach. What does this mean? You have two Vector3 values, one called renderFrom, the other called renderTo. The x-coordinate tells what radius to start and end at, the y-coordinate gives us the starting and ending angle and the z-coordinate gives us the starting and ending layer. Here is an example of what if can look like:
The only limitations are that the starting radius cannot be less than 0 and starting values cannot be larger than ending values (and vice-versa). The only exception is the angle, this is is necessary in order to  be able to draw a sector from, let's say 300° to 15° (which can be seen as from 300° to 375°).

This has been the biggest roadblock so far, now I need to do some proper testing and final polish, write the new documentation and I can submit the update to Unity. Supporting a new type of grid is a substantial effort and, since everything is interconnected, it usually requires going through the code for the other grids as well. Sometimes parts that seemed general enough might need to be overridden and other parts that seemed very specific become more general and need to be moved up the hierarchy. Considering this and the updates since the release of version 12.0 I believe raising the price to from 20$ to 25$ is appropriate.

Of course, as usual, if you already bought Grid Framework all updates are free for you. If you intend to buy Grid Framework, now is the chance to still get it for the lower price. You don't need to rush and get it immediately though, I'll post an at least one more update before I submit version 1.3.0.

As always, thank you for your support
HiPhish

2013/05/17

Grid Framework version 1.2.5 released


This release serves as a preparation for Version 1.3.0, which will add polar grids

  • The methods NearestVertex/Face/BoxW and NearestVertex/Face/BoxG replace FindNearestVertex/Face/Box and GetVertex/Face/BoxCoordinates respectively. This is just a change in name, as the old nomencalture was confusing and makes no sense for grids with multiple coordinate systems, but the syntax stays the same. The old methods will throw compiler warnings but will still work fine. You can run a Search&Replace through your scripts to get rid of them.
  • The GFBoolVector3 class can now be instantiated via GFBoolVector3.True and GFBoolVector3.False to create an all-true or all-false vector
  • Similarly you use GFColorVector3.RGB, GFColorVector3.CMY and GFColorVector3.BGW for half-transparent standard colour vectors
I apologize for the inconvenience of having to rename the methods, but I'll try to explain my reasoning. When Grid Framework was originally conceived only rectangular grids were in place. For rectangular grids only one coordinate system really makes sense, so there were two spaces: world space and grid space. Consequently, every point could only exist in either of those two.

One of the most basic needs I implemented back then was to find the nearest vertex of a point, hence the name FindNearestVertex, and later the same for faces and boxes. I also needed a similar method for grid space, I wanted to get the point's grid coordinates.
The problem arises when you start having more than just one grid space. When I wrote hex grids I always considered the possibility of having a second coordinate system aside from the herringbone pattern, and that's when I should have realized that my naming convention was... well, stupid. Polar grids will have two coordinate systems from the start, so I had the choice to either use some band-aid solution and have a naming convention that makes even less sense, or I could make a clean cut here and now.

So, what does this mean for you? At the moment nothing aside from a bunch of compiler warnings. You can just ignore them if you want, the old methods are still in place, they just call the new ones instead. I don't have any intention of removing them anytime soon, so you don't need to rush ahead and replace your old calls. The syntax has stayed the same, so running a quick Search&Replace will fix things for good.
The new naming convention goes as follows (without the brackets): Nearest[Vertex/Face/Box][X], where X stands for the coordinate system in question. For world it's W, for grid it's G and for the upcoming polar coordinates it will be P. Obviously only W and G make sense for all grids, the rest depends on the specific type of grid. You will be able to convert a point from any system into another (like PolarToWord).

I am sincerely sorry for this, but please understand that this was a necessary step in order for Grid Framework to remain clean. I always find things to improve and tweak, but most of them are under the hood and go by unmentioned, it just happened that this one was on the surface.

2013/05/10

a first look at polar grids

I've been working on the next type of grid: polar grids. The polar grid is based on polar coordinates, meaning instead of identifying a point's position using X and Y coordinates we use a radius and an angle. The radius tells us how far from the origin the point is and the angle tells us the direction. This screenshot shows the new polar grid in Unity


A polar grid is defined by three values: radius, sectors and depth. Radius refers to how far apart the red circles in the picture are, sectors is how many sectors you have and depth is how far apart each two layers of a polar grid are. Since we have a third dimension the mathematically correct term would be a "cylindrical grid", but I'll call it polar just for the sake of simplicity. If you have cylindrical coordinates just ignore the third component and you get polar coordinates. You'll notice that the angle between sectors does not define the grid, because the sectors have to cover the grid completely; you can't have the last sector be only a third of the other sectors. I'll see if I can still make the angle adjustable via an accessor.

Polar grids have a few unique quirks that differentiate them from rectangular and hex grids. First of all we now have circles instead of straight lines, but we can't draw actual circles. My solution is to add a "smoothing" option; without smoothing the red lines inside the sectors will be all straight and the grid will look like a spider's web, but each increase in smoothing breaks up the line into more segments, coming closer to a round shape. Of course increasing the smoothing means that there will be more points to calculate, but fortunately a single-digit number is already enough to get a smooth look. Also, the more sectors you have, the less smoothing you need.

A more fundamental issue rather than just a cosmetic concern is the coordinate systems. Yes, plural. The first one is the regular cylindrical coordinate system where radius, angle and height are given as absolute from the origin with respect to world dimensions. This means, no matter what you set your grid's radius, sectors or depth to, a given point will always have the same coordinates. The other one is a grid coordinate system where each component represents the relative position inside the grid with respect to radius, angle (calculated from sectors) and depth. Changing the grid also changes the coordinates of a given point.

You can convert between both coordinate systems and world space on the fly and neither system is really "better" than the other. It would be just wrong to have a polar grid without polar coordinates and it is what you want to use when moving objects in the world. On the other hand, it you want to think in "grid space", it's easier to think in terms of fields, like a board game, so grid coordiantes appear more intuitive.

At this point all the math is done and the hardest to implement methods (drawing, coordinate transformation and finding nearest vertex/face/box in all three coordinate systems) have been written. The next parts should be easier to implement, but I'm not exactly sure how to design them (what exactly does "aligning" in a polar grid even mean?). I'll keep you updated once I have more to show.

2013/04/03

Grid Framework version 1.2.4 released

Version 1.2.4 has been approved by the Asset Store team. Here are the new features:

  • a caching feature that keeps the activity of the grabage collector low now, instead of re-calculating the end points of lines every frame we can re-use them instead as long as the grid hasn't been modified.
  • a new example shows you how to create seemingly endless grids without the overhead of actually having a gigantic grid
  • explanations about rendering performance in the user manual
Enjoy the new performance improvement and thank you for your support.

2013/03/30

Seemingly endless grids and performance

I've been dealing with performance in Grid Framework recently and added a feature that will keep the Garbage Collector from going crazy. Until now rendering always went like this: Manager requests rendering from grid -> grid calculates the end points of each line -> these points get passed to Unity's GL class for rendering. Every single frame. I have introduced a caching feature that will store all the calculated points and reuse them instad of calculating everything all over again as long as the grid has not been modified.

This still doesn't solve the second bottleneck: rendering all these lines. Unfortunately there just isn't anything I can do about this, the GL class needs to have every single point one way or another. So, what if you want a very large grid that extends way beyond your camera's view? The answer is to fake it!

The idea is to only have the grid large enough to go beyond the camera's view port. Once the camera tries to go off the grid change the grid's rendering range to fit into the view port again. However, every time we change the rendering range this causes the caching to recalculate the points (since our old points are no longer valid), so caching doesn't do anything. The solution here is to add a little buffer, to make the grid larger than the view port, so we can move the camera a bit without going off the grid. Here is the video showing it step by step:

With such a small grid there is no real difference in using caching of not, but the concept is there if you need it for larger cases. This example will work in the current version of Grid Framework, but caching is a feature of the upcoming version 1.2.4, which is still waiting for approval.

2013/02/28

Grid Framework version 1.2.3 released

This update brings you two new features, both were suggested by customers. The first one is the ability to set a separate set of colours for rendering instead of using the same colours as for drawing. Let's say you want a barely visible grid in the game but a clearly visible grid in the editor. Until now you either had had to have two grids or use a script to change the colours once the game starts. Both options worked fine but required more work than needed, now you can do it out of the box. Of course it is entirely optional, so if you don't set anything you will be using the same colours for rendering and drawing.
The other new feature is relative size. Usually the size and the renderFrom/renderTo vectors were interpreted as absolute world unit lengths. I did this intentionally so the grid's size would be independent from its spacing (or radius and depth for hex grids). Of course not everyone is concerned about that sort of thing, some people would simply like to say "make my grid this many blocks tall" instead of having to multiply the desired size with the spacing. Turning on relative size now does exactly that for you. Here is a visual example where the values are interpreted as absolute (left) and relative (right) length:

2013/02/14

Unity and properties/accessors

As mentioned in the previous post I'd like to relate my experience with using properties in Unity and how to make them work properly. Properties are a C# feature and not available in UnityScript (another reason to ditch UnityScript). To help demonstrate what I mean I will be using a "circle" class.
public class Circle{
 public float radius;
}

What are properties?

As we can see radius is public and there is nothing stopping someone from putting in nonsensical values like negative numbers. Since we are in Euclidean geometry there is no such thing as "anti-length" and we need some way to restrict the value of radius to positive numbers. One solution would be to make radius a pivate member and use getters and setters:

public class Circle{
 private float _radius;
 public void SetRadius(float value){
   _radius = Mathf.Max(0, value);
 }
 public float GetRadius(){
  return _radius;
 }
}
(the underscore in front of radius is there to mark it as a member variable; it's just a convention, not mandatory) This gets the job done, but it's ugly and bloats the syntax. What we need instead is some sort of variable/function hybrid that acts like a messenger. This is where properties come in. Here is the same code as above, except using properties:

public class Circle{
 private float _radius;
 public float radius{
  get{return _radius;}
  set{_radius = Mathf.Max(0, value);}
 }
}
The property looks like a function that missing the brackets for parameters and it is treated like a variable in coding. Whenever we assign a value to it by using the "=" sign we actually call the set and when we use it in computation we call the get. value always refers to the value on the right hand side of the "=" sign. Here is an example:
myCircle.radius = -3; //calls set and sets _radius to 0
Debug.Log(myCircle.radius); //calls get and returns 0
}

Why should you use properties?

As you can see accessors allow us to expose member variables in a controlled fashion. You can put up restrictions on what a certain variable can hold. You can also create read-only "variables" by omitting the set part. Let's say your circle class has several formulae using the circumference and you don't want to type the formula every time. Here is what it would look like using an accessor:
public class Circle{
 private float _radius;
 public float radius{
  get{return _radius;}
  set{_radius = Mathf.Max(0, value);}
 }
 public float circumference{
  get{return Mathf.Pi * radius * radius;}
 }
}
There is no such thing as a "circumference" variable, instead its value is computed on the fly, yet you can still use it as if it were an actual variable:
float volume = height * myCircle.circumference;
Unity handes rotation using quaternions but you can still use Euler angles in the editor and in scripting, this is (most likely) the result of using properties as well. Properties are also great for exposing member variables in custom inspectors, like I did or Grid Framework. Unfortunately there is a problem.

Member varibles and the editor

You can treat the property just like any other variable when writing a custom inspector. However, once you hit play you will notice that your values have been reset and once you exit play mode or change the scene or anything else your values reset again. This is because the properties cannot actually store anything, they just serve to expose private members. The values of private members don't stick though, that's why everything gets reset. The solution is to use [SerializeField]:

public class Circle{,
 [SerializeField]
 private float _radius;
 public float radius{
  get{return _radius;}
 set{_radius = Mathf.Max(0, value);}
 }
 public float circumference{
  get{return Mathf.Pi * radius * radius;}
 }
}
That's it, now your member variable will get serialized and will be remembered. It took me a while to find this, but I was finally able to throw out quite a lot of ugly workarounds. And now there is no reason not to use properties anymore. Let's end this post by using properties to limit the value of a float variable to something appropriate for angles:
private float _angle;
public float angle{
 get{return _angle;}
 set{return value >= 0 ? value % 360 : 360 + (value % 360);}
}

2013/02/12

Grid Framework version 1.2.2 released

Update time. Let's go over what's new:

New example: sliding block puzzle

It might not look like much, but this is the most advanced example yet; it's similar to the movement with obstacles example where we use a matrix to store which tiles are allowed and which are forbidden. The tricky part is that now objects can span more than one tile and all of them have to be free. The solution is to break up the obstacle into one tile large parts, then check them all individually and finally assemble the answer from the individual answers.
The end result is that it feels like collision without actually using collision. Now, you might be wondering why not just use actual collision detection? For one, Unity's collision detection requires you to move objects through the physics engine instead of directly. This means instead of moving the block like you would in real life you need to use force, like dragging the block with a rubber band. This feels just wrong, especially on a touch device. If you move objects directly (i.e. using their Transform component) the physics engine is likely to miss intersections. The other reason is that Unity's collision detection just isn't made for packing objects together this tighly, sooner or later things will just randomly  fly in all directions like the puzzle exploded or something.
Don't get me wrong, PhysiX was certainly developed by talented people who know more than I do, but it was written with 3D action games in mind and trying to get it to work in such a scenrio is like trying to fit a square peg into a round hole; you might get it to kind of work well enough eventually, but in the time it took you you might as well have written your own solution which you have proper control over. Thanks to Grid Framework we can automate all the unit conversion between world space and grid coordinates.

Changes: I removed the minimumSpacing (rectangular grids) and minimumRadius (hex grids) variables because they were stupid. The reason why they existed in the first place was to prevent the user from setting too low or nonsensical values for spacing and radius. The proper way to do this would be to use accessors (also called properties), but Unity's editor scripting documentation is rather lacking, so I couldn't figure out how to make the values not reset all the time.
I finally found the solution (that's a topic for another time) and now I hardcoded a lower limit of 0.1 for both. I think that's a reasonable value, but if you need to go lower please let me know. The way it works now is that if you try to set the value to anything lower than 0.1 it will automatically default to 0.1. I was also able to get rid of other ugly parts inside the source code and clean things up thanks to accessors, but I don't think you will notice any difference
In terms of scripting this has no real consequences for you, just use spacing and radius like you did before.

Fixes: One major bug was a typo that could prevent the project from building. I also removed the redundant "Use Custom Rendering Range" flag from the inspector, now opening or closing the "Custom Rendering Range" foldout toggles the value (in terms of scripting the varaible still exists, it's just the way you set it in the inspector). Speaking of inspector and foldout, previously the state of the "Draw & Render Settings" foldout reset each time you entered or exited play mode. Now the settings will stick and it will be individual for each grid type. There is also the obligatory under-the-hoods improvements, but there is nothing particular worth mentioning there.

2013/01/01

Happy New Year

A happy new year to everyone! This has been quite a year for me, so what better opportunity to recap the birth process and evolution of Grid and set the plans for this year?

How it all began
One day I was sitting at my computer, trying to place blocks in Unity, thinking how great it would be if there was some sort of extension, a framework if you will, that would auto snap objects to a grid of my choice. Unity already has some form of grid built in, but it's rather poor to say the least. Unfortunately a quick Google search didn't yield anything useful, so was left waiting for someone who knew how to program a copmputer to make such an extension. Then it struck me: I am someone and I know how to program a computer!

The first draft
So I sat down, took out some pen and paper and started deriving th formulae. After a while I had a plan and I wrote a nice simple makeshift solution. It worked but in my head all sorts of great ideas popped up. What if the grid was in 3D and could be rotated? Would it be possible not to just align objects but construct an entire coordinate system out of it? What if the origin of the grid was not the origin of the world but any point in space? Would it be possible to have more than one grid in the scene? How about entirely different grid shapes than just squares? And if all that was possible, wouldn't be possible to use the grid for more than just aliging? Could the grid be used for actual gameplay?
The idea at the time was to get the makeshift solution polished up a bit and then give it away for free and ask for a small donation or sell if really cheaply. This idea was humble, if you want to be nice, or stupid, if you want to be realistic. Essentially, it wouldn't have made any user happy nor would it have made me money. No one would win. Fortunately the Asset Store submission got lost somehow and remembering the awful drawings I had for the Asset Store pictures, it really was for the best.

This Time For Real
The lesson I leared was that if you want to do something do it either right or don't do it at all. People will remember a halfassed effort and you will never be able to shake it off. Instead I decided to get serious this time, I switched my language from JavaScript to C#, dug into the deepest depths of the Unity documentation and learned many new things along the way. At times it was infuriating, at times it was fantastic and at times it was plain boring. Nonetheless, if I had the chance to travel back in time I wouldn't do anything differently (except for some lessons I had to learn the hard way), the experience alone of crafting something on your own and working towards a goal is very rewarding. I don't think there was anything left from the first draft, and even if it was it is all gone by now. Good riddance.
If it had been just the coding part it would have been enough already. Being a one man team however, I also had to write the documentation, design a logo, create the Asset Store promotional material and write descriptions for the Store and the forum thread. I never learned anything about marketing, but I did work in retail, this is where my exerience came in handy. On the internet I can think all day about the description text, but when it comes to talking face to face with real people your brain has to act very quickly.

The First Release
If you were to ask me what the hardest part was, I would say finishing it. There comes a point when you have to draw the line and stop adding new features so you can iron out the remaining bugs and wrap up the lose ends. There were still some left after the release though, mainly the integration into Unity's interface, no cusom inspectors for the grid classes and the complete lack of rendering. I decided to tackle those as quickly as possible, for I was running out of time.

The 1.1.x Line
I had no idea how to do the rendering and at one point I was considering imitating Vectrosity's behaviour (after asking for permission of course). Anyone who owns Vectrosity and who has taken a look at the code will be blown away by all the work of the author, there was no way I could just rip out some parts and call it a day. Instead I decided to write my own rendering solution and offer Vectrosity support as an option, since I already had a license and the two looked like a perfect fit. Both solutions work in fundamentally different ways, so users can choose the one they like best. Yay for choice ^^
After getting rendering, the biggest missing feature, and Vectrosity support out I had two things to do: many small improvements like a custom rendering range or additional functions and of course hex grids. This was during the summer when I was busy studying for exams, so my work on Grid Framework slowed down to a crawl after the first few 1.1.x releases.

Version 1.2.x and hex grids
After the exams I was finally able to devote time to Grid Framework again. The hardest part about hex grids was not so much the math, although that wasn't easy either, but how many possibilities there are to do hex grids. I already discussed this topic a few months ago, but this was a real pain. It was clear I wouldn't write several classes, so I had to design my code to accommodate for all the cases. In the end the solution was not really hard, it was the journey there, I just couldn't find anything on the internet or in any book about how to do it. What really matters in the end though, is that I was able to deliver one class for all cases, fitting right with my design principles established in the first release.

The Future of Grid Framework
Well, that's it for last year, but what can you expect for 2013? First of all, I'm working on my own website, so far it has only been this blog and the forum thread, but I would like to give Grid Framework a proper web presence. I had to learn HTML and CSS from scratch, but the site is almost done, just a few finishing touches and it should be up soon.
Hex grids have the same feature set as rectangular grids, but there is more we can do with them, most notably more coordinate systems. Expect more updates for hex grids after the site has launched. There are also a few minor features I would like to get done all across Grid Framework, so I'll add them inbetween the more important releases.
Triangular grids and path finding are next on the priority list, I just haven't decided which one would be more important. Triangular grids sound easier, but path finding seems more useful. I'll have to think this over when the time comes.

Well, that's it for this time. Have a good year 2013 and thank you all for your support :)