How to extend Grid Framework with your own methods

Let's say you just bought Grid Framework, wrote some game logic and now you want to reuse it. Wouldn't it be great if it was a class method in Grid Framework so you could simply call it with one line of code? Even better, what if you could have one method that has the same syntax for both rectangular and hexagonal grids but different implementation based on the type of grid, so you would have to write just one script for any type of grid? Luckily this is no problem in Unity thanks to extension methods and if you have the code, then wrapping it up into an extension method can de done in a few minutes. Take a look at my latest video tutorial:
Extension methods are only available in C#, but once you've written the method you can use it in any of Unity's scripting languages. Aside from keeping your code cleaner, extension methods have the advantage that if you need to make adjustments to your game logic you only need to do it in one place and every call of the method benefits from it.


Hex Grid introduction video

I made a short video giving you an overview of hex grids, so you can see them right in action. I'll make a video on how to extend Grid Framework with your own methods yourself next,


Grid Framework version 1.2.0 released

The wait is over, version 1.2.0 is out, bringing you the long promised hex grids. I'll soon make a video demonstrating the new grid, in the meantime let me explain it in words. My implementation brings you all the features you knew from rectangular grids, except on a hex grid, and both grids inherit from the same base class. This means the API for both is the same and you can write one script for both grids with little to no need to make special adjustments for differentgrid classes. Currently there is only one coordinate system and hex grids have "only" as much functionality as rectangular grids. I whish to improve upon this in the future.

Phew, this has really exhaused me. Often times I was wondering what I had gotten myself into and it was not uncommon for me to work beyond midnight, pondering above pencil-drawings, deriving formulae and thinking how to make everything work nice. The last stretch has been especially tiresome, getting the computer to do something is one thing, but then you start putting together the manual and you notice that the way it *how* it works doesn't feel right. It's those little thing no one notices when they are done right but everyone notices them when they are done wrong. What kept me pushing forward are you guys and your support. Many of you are silent, and that's fine, but I know you are there. Thank you.

Grid Framework version 1.2.0 submitted

Just a quick update, version 1.2.0 has been submitted. This is your last chance to buy the package for 15$, once it has been approved the price will be raised to 20$.


Grid Framework version 1.1.10 released

The 1.1.10 update brings in a new function, ScaleVector3(Vector scl) : Vector3 which takes in a vector and then scales it so it fits inside the grid. This is similar to AlignVector3, which was introduced in the last update, to allow performing the aligning and scaling without having to provide an actual Transform.

In other news, the hex grids are almost done. All the functionality has been written, now I need to clean everything up and write the documentation. Hex grids will be officially introduced in the 1.2.0 update, which I expect to release within the next week or, if something goes wrong, the week after. Unfortunately, due to all the work I have put into Grid Framework since the first release I cannot charge 15$ anymore, starting with 1.2.0 the price will be raised to 20$, so if you want a copy of Grid Framework, now is the time to get it. When I originally released Grid Framework there were still many loose ends and it was not integrated well into the workflow. When you downloaded it from the Asset Store you had to move files manually in place, there were no menu entries, you had to drag a script manually onto objects, there was no custom inspector panel, there was no rendering, no Vectrosity support and less examples included. Over the time I have been adressing all these shortcomings and improving, but none on its own felt like they were justifying a price increase. With hex grids I'm bringing in a major functionality update and I believe the 20$ price tag is still well justified. Of course anyone who has already purchased Grid Framework will get this and all future updates for free, that was the deal when I first launched it and nothing is going to change about that.


How about herring for lunch?

Another progress update: WorldToGrid and GridToWorld are now implemented. For those who don't know, those two functions convert a point's coordinates from world space to grid space, the coordinate system used to locate points relative to the grid's properties, and back. For rectangular grids it's a fairly simple idea, the grid can be represented as a standard Cartesian coordinate system. With hex grids that won't do it, you simply cannot force a hex grid into a cartesian coordinate system, you need to find something else. Fortunately there are several topologically identical possibilties whith easier, more intuitive coordinate systems. For the first release I have decided to use the herringbone pattern:

The vertices of this pattern are the faces of the hex grid. This means the central face has coordinates (0, 0, Z) and the face north-east of it has the coordinates (1, 0, Z). This way each single point of the hex grid can be canonically identified by its coordinates. "Canonically" means that no two points have the same coordinates and no two coordinates represent the same point. As a side effect this gives me an all new grid to work with, although the herringbone grid will have to wait until later before it gets the proper treatment.

This brings me almost concludes the hex grid development. The only things left now are the vertex matrix methods, testing and fixing everything to make sure it's reliable and then writing the documentation.


Trying to fit a square peg into a hex hole

The align feature has been giving me quite some headache lately. For small objects it's easy, just fit them inside the nearest hex. It gets more interesting once your object spans over more than one hex. Here is a screenshot from the game "Age of Wonders" for PC (I upscaled the image manually, AoW has a very low resolution)

As you can see the city goes over two hexes and no matter which of the two I click, I always select the city. I tried many ways of calculating a resonable way how to fit such an object into a hex grid, but no matter what I tried, it was bloated, had many cases and, worst of all, didn't really make any sense. The way Unity is designed is to work with rectangular objects which might be rotated. In a hex grid system everything is rotated, but only from our point of view, in terms of game logic everything is the normal way. This is what is causing problems, I'm trying to force one viewpoint into a different context.

So, what's the solution? I decided to go for the easiest and most intuitive approach: each object will be placed into the centre of its nearest hex. What about objects that need to go over two fields? In that case the user would have to set the pivot point manually, either in the 3D modelling aplication or in Unity by parenting the object to another object and placing them relative to each other so the pivot object is where you want the pivot point to be. In fact, this is exactly how the Age of Wonders editor is doing it.

You'll get a better idea of what I mean when you see it in action. In this video I'm assembling the structure directly inside the editor. Note that only the parent spheres have Rigidbodies, but all spheres have colliders and the script. Unity is designed in such a way that if an object has no rigidbody calling "rigidbody" will return the RB of its parent. Thus it's always as if I clicked the parent sphere when I click any sphere of a structure.

I think this is a good solution. Unless I somehow come up with a better way to do aligning this is what I'm going to stick with.


Grid Framework version 1.1.9 released

Surprise update! Version 1.1.9 just got approved and it contains quite a few changes:
  • NEW METHOD AlignVector3: lets you align a single point represented as a Vector3 instead of a Transform to a grid
  • added the ability to lock a certain axis when calling AlignTransform and AlignVector3
  • added a new constructor to both GFBoolVector3 and GFColorVector3 that lets you pass one parameter that gets applied to all components
  • you can now lock axes in the Grid Align Panel as well
  • aligning objects via the Grid Align Panel which already are in place won't do anything, meaning they won't create redundant Undo entries anymore
  • fixed an issue in GetVectrosityPointsSeperate
  • renamed the classes BoolVector3 and ColorVector3 to GFBoolVector3 and GFColorVector3 to avoid name collision
  • size has always been a member of GFGrid, not GFRectGrid, I fixed that mistake in the documentation
  • minor clode cleanup and removing redundant code
The first two are based on a user's suggestions, thank you for bringing those up. Previously when you wanted to align a Transform it would be aligned along all the axes, but now you can set certain axes to be left as they are (relative to the grid's local space). Also, instead of aligning a Transform you can also just align a Vector3 now, this is useful when you only need to calculate a position. You need to specify a scale, which was previously taken straight from the Transform, but I've set it to default to (1, 1, 1) so in most cases you won't have to think about it. Of course the Grid Align Panel lets you lock axes as well now. Since the option is passed as a GFBoolVector3 I added a new convenient constructor to the class that takes only one parameter and sets all entries to that. The same goes for GFColorVector3.

Another improvement is that objects which are already in place in the editor will be ignored by the Grid Align Panel when you try to align them. The reason for this is that before, if you had set the Autosnapping flag and clicked on an object that was already in place it would create an Undo entry even though you didn't see anything happening. Now there will be an Undo only if something happened.

The function GetVectorsityPointSeperate had been broken due to a few typos since release and I've only noticed it a few days ago. I guess no one was using it yet, so it went unnoticed for quite a while. It definitely works now.

The rest is just some under the hoods maintenance, moving code around, removing redundant parts, updating the documentation, the usual stuff. None of it has any impact on stability or performance, but it is important to keep things clean when I finally release the Hex Grids.

That's it for now, please enjoy the new features.


how to loop through a list and remove items

The other day I had the following problem: I had a list of Transfoms and I wanted to remove the entries that met a certain condition. This is what I had written:
 foreach(Transform trns in transformList){  
This gave me the following error message: InvalidOperationException: Collection was modified; enumeration operation may not execute.

This makes sense, I'm modifying the list I'm currently reading and there is no way I can be sure I'll catch all entries. There are three ways around this problem: The first is to use LINQ (C# only), the second is instead of removing the entries at once to store them in a separate list and then use that list in a second foreach-loop to remove the entries from the first list and the third solution is to use a for-loop. After some reseach I reached the conclusion that the for-loop is the fasted way to achieve the needed results. Here is the code:
 int counter = transformList.Count;  
 for(int i = 0; i <= counter - 1; i++){  
           i --; //reduce the indexer because we removed an entry from list  
           counter --; //reduce the counter since the list has become smaller  
First of all we need to know how many entries the list has initially. I could have used transformList.Count in the loop directly but this way I don't have to call the Count method for each iteration. Then we set up the loop, we start at index 0 and go to counter - 1 (because the index starts at 0 instead of 1). We perform our check and if it succeeds we remove the entry with index i. Since the list has now been shortened we need to reduce i because an item that has been at a position of 7 for example is now at position 6 (assuming that i is less or equal to 6 in this case). We also need to reduce our counter because the length of the list has been shortened as well.

As you can see the amount of lines has been doubled, while using LINQ would have left the code short. If you know that your list will always be small enough I'd go for the slower but shorter approach. In my case though I have no idea how large the list will eventually be, so using the for-loop makes perfect sense. I hope some of you find this useful in the future.


Hex Grids love Vectrosity

I got the Vectrosity support up and running for hex grids, see for yourself:

This turned out less painful than I expected, a nice change for once. On to the next task.


Vertex progress

Good news at last, I just finished the finding functions for vertices, both in grid space and in world space. Here is a screenshot where the yellow gizmo indicates the vertex closest to the grey sphere.

This may not seem like much, but being able to find faces, boxes and vertices is essential because the other functions rely on them. That's it for now, more updates to come soon.


Back again

I just wanted to drop a line saying I'm back to work. As I mentioned previously I was busy with exams, so development ws slowed down and during the last couple of weeks I had to stop completely to concentrate on studies. Now that it's over I can get back to working on the hex grid update. Currently I'm about halfway done, maybe more. I'll keep you updated :) Finally, I'd like to thank everyone who bought Grid Framework so far, you guys have made all this effort worthwhile and you are the ones who allow me to go on with it. Thank you.


example video: Level Design and Text parsing in Unity3D

I made another example video for Grid Framework, this time for the recently introduced text parsing example. Now building new levels is as easy as writing a few lines of plain text and you get perfect clockwork-like precision. This opens up new possibilities for faster development, easier maintenance, easier level editors and support for user-made content. Just take a look at how simle, yet effective it is:


Version 1.1.7 released

Version 1.1.7 has been approved by the Asset Store team. I fixed a small typo that prevented the menu item for adding the GFGridRenderCamera component from working and I added two more examples,  video tutorials will follow soon. I also redid the screenshots because the Asset Store ate my old ones somehow.
The first example shows you how you can use a plain text file and Grid Framework to build levels outside the editor. If you have a game like breakout that's heavily based around grid-based design it would be tedious to design each level via Drag&Drop in the editor. Another disadvantage is that changing the level would mean switching the scene and it would be harder for players to create their own levels as mods. In my example we design the level as a plain text file where each character corresponds to one predefined prefab. Then we need to set up only one scene and the text parser script will, along with the grid, take the text file, read it and then place blocks accordingly. You can even switch levels on the fly without changing the scene.
The second example continues the grid-based movement example by placing obstacles on the grid. One way to avoid them would be to attach colliders to the obstacles and then have the walker perform a line cast in the direction of its movement and see if the line cast hits anything. However, since this is Grid Framework we can do better than that. In this example I create a matrix that stores whether a tile is forbidden or not and then the walker checks if its next target square is alowed or not. There are no colliders or physics used.


Cannot log into my account

I've written two new examples, one that takes a plain text file and parses it to create a breakout-style level based on a grid without changing the scene, the other is a continuation of my grid-based movement exmple where I can place obstacles on the grid and the sphere will not step on those squares (without using any physics like collision and raycasts). Sadly I can't update Grid Framework because I can't log into my account via Package Manager. My account still works, I can log into the forums and my Publisher Administration, so the problem must lie within the editor. I've submitted a bug report, but until then I cannot publish updates. If you are interested in one of those two examples please contact me over the Unity forums and I'll send you the examples, provided that you already own Grid Framework. On a related note, it appears that Grid Framework's product page in the Asset Store doesn't have any screenshots. I did submit screenshots, but they don't appear for me, I don't know if other people can't see them either.


Version 1.1.6 submitted

Important Note: The classes Grid and RectGrid have been renamed to GFGrid and GFRectGrid, you will need to change your source code accordingly.

You might be wondering why I would do such a thing more than one month after releasing the package. Using regular English words is simple and intuitive; however, the danger of name collision with another class called the same is quite large. Let's say a user has already a class called Grid for something in his or her project. When they buy Grid Frmework all of the sudden they will get compilation errors because now there are two classes called Grid. It would be unreasonable to expect users to change their class, especially if that class is already part of a more complex chain of dependencies or inheritance. They could change my code, but then they would have to change it after each single update of Grid Framework. If the class Grid is already defined in some other third party extension it gets even worse.

Adding the GF in front of both classes reduces the chance of name collision. I apologize to all my existing customers for having to change their source code because I didn't think about this in time, but I had to resolve this before it becomes an issue and the sooner I get it sorted out the less customers will have to change their source code. I am very sorry, but this should fix the problem once and for all.

Aside from that the GFRectGrid class contains some minor code cleanup and performance boosts, so it's not all bad news.


Version 1.1.5 released

As per request the custom rendering range now affects drawing as well, not just rendering. If you are wondering why this wasn't the case before, it was a leftover from before the custom rendering range got implemented. Originally the custom range was only meant for rendering because that would be what the layer sees in the final game, not the drawing, whether they are the same or not. Also, the drawing is only a drawing, the grid keeps working beyond what's visible, being infinite. That's why the drawing had low priority and I worked on other parts instead.


Version 1.1.4 released

Version 1.1.4 has been approved. It doesn't add anything new for a change, instead it fixes a bug where lines with a width larger than 1 were drawn on top of things they were supposed to be under.


Hex grid progress so far

Here's a quick status update:

  • Drawing: This works perfectly now, the hexes are drawn properly as described in the post before, and now i have added lines that connect the different layers of the grid.
  • Rendering: Like drawing alsmost finished, except one minor issue. In the rectangular grids you can specify a width for the rendered line and, since the line is drawn in 2D, I had to calculate the directions in which to expand the lines. There were only three possible directions and the lines were sorted by X, Y and Z, so it was enough to calculate each of the three directions only once. With hex grids one set of lines is zig-zagged, so I need to calculate four directions total. I need to find a nice way to separate the the two differently slanted lines. I don't want to calculate the direction for every line as that would be a waste of ressources.
  • Find nearest face & Get face coordinates: done, although only for the default coordinate system.
  • Find nearest box & Get box coordinates: done, just like above

This leaves the following functions:

  • Find nearest vertex & Get vertex coordinates: The challenge here lies in finding a nice coordinate system, and by nice I mean one that's intuitive to understand, easy to implement and easy to maintain
  • Build vertex matrix & read vertex matrix: Getting the vertices is already done, the challenge again lies in finding a good coordinate system.
  • Align & Scale transform: shouldn't pose any problems
  • World to Grid & Grid to World: you guessed it, deciding on a coodinate system
  • Get Vectrosity Points: This will take the same points as used by rendering and drawing, but the array has to be processed first to fit Vectrosity's requirements

So, all in all it looks pretty good. Unfortunately progress has been dragged down by my studies, I'm writing exams soon, so I can't afford to work on Grid Framework full time. The plan is to finish all the needed functionalityl for the first release. After that additional coordinate systems will be added and after that I'll add more drawing shapes like triangular and circular hex grids. That will conclude the hex grid chapter of Grid Framework.


Hex grid drawing - finally!

I have finished the drawing part for hex grids. As I mentioned before, there are many ways to draw hex grids and I want to cover as many of them as possible. Let's count all the possibilities that work now.
There are three plains to draw on, the XY-, XZ- and YZ-plain. In each case you have the choice of having pointy sides or flat sides, those are two possibilities. Every second line is offset upwards, so you can either draw those offsets or keep the grid compact, so two more choices. Each grid can begin with an offset colum or not (two more) and end with an offset column or not (again, two more). That's a total of 3 x 2 x 2 x 4 = 48 possibilities! On top of that no line should be calculated more than once, or else it would be drawn twice. That may seem trivial, but if your lines are semi-transparent the difference between lines drawn once and twice can be seen.
Needless to say I don't want to write and maintain 48 similar algorithms, everything has to be handled automatically by one single function. Eventually I got it, it works with any of those possibilities. I've prepared four variations of the same grid to give you an idea. The upper ones are the pointy sides, the lower ones are the flat sides. The left ones are fully drawn, the right ones are compact.
There are also other ways to draw a hex grid, as a rhomb, a triangle or a big hexagon made from smaller hexagons. I will do them after I have the scripting functionality done, drawing is independent from the other calculations.


swap variables in Unity

I've decided to go with one HexGrid class and provide enough options. To do this I will need to swap around variables so I can use the same formulae for different cases. I could write the swapping part where it is needed, but then I'd be writing the same thing several times (which is a bad thing to do). Wouldn't it be better if there was some sort of swapping function? Could that function work for any type of variable? Could it work without needing to reassign variables again? Yes to all of that:
 void Swap<T>(ref T a, ref T b){  
      T t = b; b = a; a = t;  
It works the usual way, you create a temporary variable, assign one variable to it, then assign the second to the first and the temporary to the second. The T stands for the type, this is a generic function, meaning you can use it for any type you want. You can swap int, float or even something crazy like Collider or something usermade. The ref means that the changes done to the variables in the function are reflected right back. Usually a function "copies" the values passed and leaves the original variables untouched. To use the code you would write something like
 int x = 1, y =2;  
 Swap<int>(ref x, ref y);  
There are some tricks floating around on the internet without the use of a temporary variable and using math tricks instead, don't use those. At best your code just gets ugly, at worst you even get worse performance. Also, you are limiting yourself to numbers only, whereas this Swap function works for anything. Hooray for generics!


The current roadblock

It has been over a week since my last post, so I might as well explain what's going on. As I finished rendering I had tightened up all loose ends that were left, I consider Grid Framework to be complete for rectangular grids. You can perform all the common calculations, debug things and visualize the grid properly, either using simple lines or even Vectrosity. This is just the first step though. Hex grids are very popular for games for various reasons, so it makes perfect sense to do them next, right? Well, here is where the problem starts.

See, while making Grid Framework there are several challenges I need to face (let's just ignore things like documentation or presentation for now). Obviously I need to code the whole thing. I also need to figure out the math for how to even do these calculations. None of those are really any big secrets, the math has been there for centuries and the coding part is just turning verbose instructions into C# code. It's a pretty straight-forward process, more or less, once you figured out what to do and how to do it. And that's where the current challenge lies.

Rectangular grids are relatively simple. Being in 3D and able to rotate and translate and having individual spacing made them more complicated, but it was still the same basic formulae, just more expanded. Hex grids are not as easy, simply because there is more you can do with them. This leaves me with some really nasty design decision.
When writing an extension I need to keep in mind that it will be used by lots of different people who might have different ideas about what a hex grid should work like. Some might want to fit a grid inside a rectangle, like in battle for Wesnoth, others might want one big hexagon made of smaller hexagons, like in Settlers of Catan. I cannot just pick one and tell the others to convert their game to the other type. This also raises the question of coordinates. A rectangular grid is just a standard cartesian coordinate system with some stretching and squeezing. I can even have fractions of a coordinate to give a precise position. If I fit a hex grid inside a rectangular grid, can I still have fractions? Do I even want such a feature? What should the coordinates represent, vertices or faces? What about the pointy side of a hexagon, is it one unit or just half a unit? Speaking of which, how does everything change if I want the tops to be pointy instead of the sides? Where should the origin lie? How many axes should even be there? (don't laugh, once concept uses four dimensions)

All of these questions can be answered, that is not the problem. The problem lies in answering them all in a way that is clean to implement, clean to maintain and clean for the end user to use. Should I make different hex grid classes, which would be easier to code, but would mean more code to maintain and more API for the user? I would like to just start coding and see what happens, but these questions need to be answered first, or the code will explode right in my face. I don't know how long it will take, but I'm working on it.


Version 1.1.3 released

You know, sometimes I look at something and wonder "what kind of idiot designed this!?", only this time I was the idiot. Let's say you wanted to render a simple 3x3 grid and you wanted the origin to be in the lower left corner. Well, you simply couldn't do that, not until now:
Instead of using the size you can now specify your own range, the only limitation is that From has to be less than To obviously. As a nice extra touch those two fields will only appear when you you choose to use custom range, otherwise they will be hidden and won't clutter your view.

Important note about updating: Until now you got one folder and had to move the Plugins folder to the root of your project view manually. This is no longer the case, Grid Framework should now place all files in their proper directory without you having to do anything. If you have an older version of Grid Framework and get errors or warnings please delete all your old Grid Framework files. This is the last time you will have to do anything manually.
I am sorry for this inconvenience, but there is some common misinformation that all assets must be in one folder. The fact is you can send your entire "Assets" folder and the Asset Store Tools will be ignored.


Version 1.1.2 released

It's up, version 1.1.2 brings Vectrosity support, better documentation and integrates Grid Framework into the menu bar. From now on you will never again have to drag scripts manually from the Plugins folder onto objects when using Grid Framework.
If you want to try the Vectrosity examples please uncomment the scripts. I had them commented so they wouldn't give errors to customers who don't have Vectrosity installed.


Vectrosity progress

Well, it's pretty much done, you can now get a set of Vector3 points for use with Vectrosity from just one line of code. I played a bit with Vectrosity to make an example scene and this is what it looks like:
(yes, I am a sucker for laser lines)
The green grid just hangs there and rotates, the red grid bounces around (using Unity's physics engine), the yellow grid resizes itself all the time and the colourful grid changes the colours of its lines randomly. The "missing" lines in the last grid lines are not a bug, they are sill there but coloured black.

I expect version 1.1.2 to be the last feature update before adding Hex Grids, so I want to wrap up all the loose ends I might still have left. In particular I want to integrate the components into Unity's main interface, no more dragging scripts onto GameObjects.


line width for rendering

I just submitted version 1.1.1 (update: has been approved) which lets you set the width of the rendered line in the inspector. Here is an example, obviously it's over the top, but you can set the width to anything you like.

Now I just need to provide a nice function to pass rendering points to Vectrosity. I'm sure those of you who own a Vectrosity license would like to be able to combine the best of both. I promise when I'm done it will be the last time you'll see me talk about rendering for a while.


Version 1.1.0 out now - rendering included

Unity just approved version 1.1.0, which includes the new inspector panel and the rendering setup. Now you can see your grid in the finished game, no pro license or any other addon needed.


a new inspector

Well, I wanted to do this sooner or later anyway, so I made a custom editor for the rectangluar grid. Before this I was using the default inspector panel:
So, why am I doing GUI stuff if I'm supposed to work on the rendering? Well, as I said I need to clean up the code, which involves looping through two custom classes of mine, ColorVector3 and BoolVector3. If you used Vector3 you know you can access values using something like myVector.x, but you can also use an index instead: myVector[0]
I wanted to have both in my two classes so I could loop through them in one go rather than write a special case for each entry and provide an intuitive syntax for users. The solution was using an indexer, setters and getters. They all work fine in code, but I cannot get getters and setter to display in the inspector and manipulating the entries directly could break things. The solution was writing my own inspector from scratch.
Aside from now being able to provide a safe and clean way to set colors and toggle axes the new inspector looks cleaner and the attributes are sorted in a way that makes more sense, rather than the way the class is built. I'm still not satisfied with some parts, the axis colours don't have labels and the the hide axis flags should be on the same line, like the Vector3 field. However, if I force them on one line or add labels to the coulour flieds the space for the labels is so large that the controls start overlapping, so it looks even worse than before.

Anyway, it does look better now and gives me the code improvements I need for clean rendering, so all in all it's a success.


grid rendering progress

Take a look at this:
What's so special? Look at the upper right corner, gizmos are turned off. This is a grid rendered at runtime that would be visible in a released game. There are still some things to care take of first: For one, the grid needs to get rendered every frame, which is not a big deal when using the GL class, but a Vectrosity-like approach where a mesh is built only once and then drawn once until it updates would be pretty neat. Also, the GL class doesn't let you set the width of lines, I could draw quads instead, but those are only thick if you look directly at them, otherwise they get thinner until they become invisble (in other words, they are flat). Lines are always the same, no matter the angle or distance, which could be exactly what you want or not. Maybe I could include some way for users to use Vectrosity easily if they have a license? In any case, I need to finish this first. The code is still very messy, being in large parts copy-pasted from the drawing code (which was kind of messy itself) and copy-pasting code is a sure way to have your project explode right in your face. I'll need to write a method to return a nice list of points that both drawing and rendering can use.


version 1.0.1

If you tried debugging the functions FindNearestFace() or FindNearestBox() you might have noticed that the cubes drawn didn't have the same rotation as the grid. While it didn't change anything about the returned value (only the centre of the cube mattered), it looked ugly. I've submitted a small update that fixes the rotation:
The update should get approved soon.


grid-based game logic

Another video tutorial, howing how to use grid-based game logic in a puzzle game. This is the tutorial for the lights-out game I mentioned before and which has been included with the package.
This tutorial is written in C# because it uses delegates and events. The reason why is so that no single tile needs to know about the other tiles, making this code extremely flexible, you culd even change your scene during runtime. If you don't know about delegates and events I really recommend you to check out prime31studios' video. Their video series really got me into C# development.
To give you the basic idea, events and delegates mean that somewhere somehow something happens and some other objects react to that. The object that triggered the event itself has no idea who (if anyone) is listening and how they will resond. For example you could have an RPG where when you draw your sword it makes villagers run away and guards draw their own weapons. Your hero would not need to know how many villagers and guards (if any) are around, he just needs to fire the event and all listeners will react accordingly.



Grid Framework has been approved and is fom now available on the Unity Asset Store for 15$
This is the price for the initial release, it will go up as the amount of features increases, but all existing customers will get all updates for free. Please feel free to visit the support thread and drop me a line if you have any questions or suggestions. Once the first wave of purchases has passed and if there are no issues I will start working on either hex grids or grid rendering, whichever you guys might find more important.

And to think that is has already been four months since I started this blog... the framework has gone quite a long way from a quick&dirty solution I rolled up in two days to something I can proudly announce. I am looking forward to an even brighter future for Grid Framework.


grid movement and runtime snapping

Well, I just sent my second submission. There are three examples included, one showcasing grid-based movement, one showcasing how to place objects on a grid during gameplay and the lights-out game mentioned below. i also made tutorial videos for the first two, showcasing how you can accomplish these tasks in a simple manner on your own:


a quick update

I have been contacted by an Asset Store admin, who recommends me to include a demo scene so users could see an end setup. I thought dragging a script onto an object is pretty straight-forward, but I agree, a demo scene would be a really good idea. The tricky party is coming up with good ideas; don't get me wrong, I have plenty of ideas for actual gameplay examples, but for a demo scene I need something more basic and at the same time more catchy. I already made a little sphere that randomly roams a grid face by face, stays within limits and immediately adapts to changes in the grid, all with just 32 lines of code total (not counting whitespaces and comments). I'll come up with two or three more nice demos, that should give a good impression of Grid Framework  in action.


Almost there...

Well, it's alsmost done. Again. Turns out that making an asset is only half the job, you still need to hammer out any ugly dents, polish the thing and then change your job to become a graphic designer, a video commentator, a writer and a salesman! What good is the best asset if you present it in such a way that makes people not even want to take a look? I'm not claiming that I'm an expert in any of those fields, but I believe I did a pretty good job (well, maybe my voice work for the video could use some improvements). In a way I'm glad the old "images" I had prepared for the first version are now lost forever, that was something to turn people away forever. You cannot imagine how awful those looked.

Anyway, I finished the videos, I made the drawings for the asset store and I wrote the documentation. The only things left now are uploading the videos (which will take quite a while with my connection), writing a description text for the asset store (shouldn't be too much, so it won't take too long) and then sending the files over to Unity. In the meantime, please enjoy a small teaser:

Unfortunately clicking this won't do anything. Yet.


Turn off the lights!

Here is a nice little puzzle game made using the grid framework. When you click a square that square and the four adjacent squares flip their color. Your task is to turn them all off.

The entire game uses only two scripts with a total of 70 lines of code. Sure, that may not seem like a small amount, but keep in mind that almost half of that is just whitespace and comments for better readability. The other half is mostly just to handle the user's input and only two lines are used for grid-based operations, i. e. finding out which tiles to flip. What's even better is that this works for any setup, you can even have holes and weird apendages like in the above picture. You could even move tiles during gameplay or generate the puzzle dynamically rather than by hand every time. Grid framework always finds the right tiles for you.

I will put up a video tutorial eventually once the package is released. I used delegates and events, so if you don't know what they are take a look at prime31studios' video tutorial:


State of the Game

It has been over a month since I posted the introductory video and sent my application to Unity. I never received any confirmation, so I assume it got lost somewhere along the way...
Anyway, that doesn't mean I have been sitting here for over a month staring at the screen and refreshing my mail. I started working on this project because I needed a simple solution for one certain problem, that's how I started working and over time more and more ideas came to my mind. It was clear that I would need a complete rewrite sooner or later, so I decided to release a simple version first and then start the rewrite instead of throwing everything up to that point out the window.

When I sent my submission to Unity I was done with the old concept and started working on the new, more robust concept that would allow for far more features to be implemented cleanly. This meant switching to C# (since some things just aren't possible in UnityScript) and diving deeper into the documentation than ever before. I like the results. I set myself a few goals and so far I have achieved most of them. This includes:

  • grids as components instead of plain classes
  • fully support 3D grids and rotation
  • functions to find vertices, faces and boxes with just one line of code
  • a nice panel for aligning and scaling instead of that dirty workaround
  • switch between grid coordinates and world coordinates (and vice-versa) with just one line of code
  • every kind of grid (quare grid, hex grid, triangular grid) inherits from one common Grid class
Most work has been done under the hood to keep the code clean. It's easy to insert a new feature into clean code where I can leverage already existing methods instead of having to write the same thing several times (copy-pasting chunks of code is an awful idea!).
The one thing that still needs a good look are the methods related to the vertex matrix, it's one of those things that are easy to break if you aren't careful.

That said, once it's done the (hopefully now) first release would be ready to ship. I'd also have to rewrite the entire documentation and draw new logos for the Asset Store (in a way I'm glad my first submission got lost, those "drawings" were just aweful)
The fist release would only cover rectangular grids with hex grids added next, then finally triangular grids. I haven't started implementing them, but I have already done the math and I know how to do it, I just need to finish this first. The one last thing I can think of is grid pathfinding, but I won't even waste a thought on that until I get the other stuff done.


Introduction video

As promised, here it is:
[video deleted]
A basic overview of what the first release has to offer. Stay tuned for future updates. The package is waiting for approval now.



Hello everyone :)

I have been working on making a 2D platformer in Unity in the spirit of the old 8 Bit and 16 Bit games such as Super Mario and Sonic. One thing I really admire about those games is their sense of clockwork-like precision, you never feel cheated by the controls, you always know which jumps you can make and which ones you can't.

Part of this precision comes from how these games can easily be broken up into blocks. For example Mario is either 1x1 blocks or 1x2 blocks large (actually it's slightly less, but let's not get lost in details here), he can jump a certain height and certain distance at a certain given speed and the level designers can easily calculate how many blocks they need to use to make the game just challenging enough to be fun but not unfair.

Consequently, I would have to do the same thing. I would need to come up with a certain block size (let's say 1x1 in Unity units) and adjust the scale and position of everything accordingly by hand. Not fun at all. Wouldn't it be awesome if Unity had some sort of grid framework, some way of specifying the grid's spacing and origin and just have the computer do the rest? Couldn't the computer scale and position my blocks inside the grid instead of me?

Well, if you need it, then make it, that's what I told myself. After coming up with an approach and a long-term plan of what to do I made the first step, a 2D grid class that can be used for scaling and alignment. The script will match you objects as closely to the grid as possible, so if your block is slightly larger it will shrink and if it's slightly smaller it will grow. With just a single key combo you can turn this messy Breakout field
into this clean arrangement

Actually, it took me longer to put those blocks into the scene than to align and scale them. As you can see some blocks didn't even have the right proportions.

Of course aligning and scaling is not all this is good for. As I mentioned before, the 2D grid is a class and as such can be used for scripting as well. The functions for scaling and aligning are built into the class so you can perform these actions during runtime. You could use the grid for path finding or anything you want. Every grid contains a matrix of its vertices, allowing you to instantly read any point within a specified range just by providing the coordinates, no math needed. Every grid is infinite in size since it's only defined by origin and spacing (the vertex matrix obviously isn't infinite) so there are no limitis to how far you can go with this grid.

I'm currently doing some polishing and fixing minor bugs. A promotional YouTube video will be coming soon, I finished writing the script, now I need to record it. Once I'm done the assets (including the documentation with scripting reference) will be avaible in the Unity Asset Store for an affordable price.
The future plans are to properly support 3D grids with rotation, make the interface more convenient, have mouse snapping in the editor, hex grids and whatever else I can come up with.


Something's coming...

OK, let's test this new blog thing...
behold the beauty of infinity...