OpenStreetMap in Unity3D

This time I have something a little bit different; OpenStreetMap in Unity3D!

If you don’t know what OpenStreetMap is (well I didn’t until last week); it’s a crowd sourced map api created and supported by what seems to be a quite big community. So you can think of it as an open source (and free) Google/Bing Maps. And it gets even better, there are many other smaller projects/services built upon OSM data, specializing in certain fields like metropol maps, metro maps etc. All these data under ODb License. How awesome is that?

So that is pretty much how I found about Mapzen and their Vector Tile Service, which by their own description “provides a free & open vector tile service for OpenStreetMap base layer data, with worldwide coverage updated daily, available in GeoJSON, TopoJSON, and binary data formats”.

I won’t go into detail about their service, format and everything but you can read all about it in their wiki page. What I’ll do though, is a walkthrough of parsing and visualizing their data in Unity3D so when we’re done, it’ll look something like this;

On the left, you can see the original OSM view and on the right, it’s the same data in triangles and debug lines… well yea I know I kinda suck at visualization.

Some bullets before we get started;

  • Note that I’ll just go over some important parts of the chode here, not the whole thing. You can find the project files at the bottom of the page anyway.
  • We’ll have to use three different coordinates systems and convert values back and forth to make this happen. First of all, we obviously have longitude & latitude, then we have OSM tile coordinate system (origin at top left) and finally the 3D space coordinates in Unity3D, starting at bottom left (XZ plane). So you’ll see lots of conversion method calls and y axis sign chances through out the code. Becareful with those.
  • You can use this nice tool to find the tile you need; PHPCalc for OMS. It’s a must-have tool if you’re planning to use OSM in your project.


Also TMS (Tile Map Service) might be a little bit confusing at the begin but it’s actually just a grid system on a mercator projection. Only thing is, this grid has different detail levels. At level 1, it divides whole thing into 4 sections, at level 2, it’s 16 etc. Try these and you’ll get the idea; (0,0,1), (0,1,1), (1,0,1), (1,1,1). Those are x coordinate, y coordinate and detail level respectively. As you can see, just those 4 tiles covers up the whole world map in level one but that number increases really fast as the detail level increases.

For this post, I’ll use detail level 14 and 9685/6207 coordinates (yeap, my neighbourhood); so  (9685,6207,14).  But of course, that’s just an image of the data they provide, the real thing is actually here. That’s actually a readable link and goes like, “get me the building and road data for detail 14 at 9685×6207 coordinates”. I highly suggest using a JSON reformatter to be able to read it though (i.e.

So let’s get started;

public IEnumerator CreateTile(World w, Vector2 realPos, Vector2 worldCenter, int zoom)
    var tilename = realPos.x + "_" + realPos.y;
    var tileurl = realPos.x + "/" + realPos.y;
    var url = ",earth,buildings,roads,landuse/" + zoom + "/";

    JSONObject mapData;
    if (File.Exists(tilename))
        var r = new StreamReader(tilename, Encoding.Default);
        mapData = new JSONObject(r.ReadToEnd());
       var www = new WWW(url + tileurl + ".json");
       yield return www;

       var sr = File.CreateText(tilename);
       mapData = new JSONObject(www.text);
    Rect = GM.TileBounds(realPos, zoom);

This is the entry point for whole process. Let’s have a look at it; it returns IEnumerator because I’m using WWW object and calling this function in a coroutine. Then we have 4 parameters; World is my main script to handle environment related stuff, not really necessary here. realPos is the x,y coordinates of the tile in TMS system (so 9685,6207). worldCenter is where we’ll create this tile in Unity3D space (it’s Vector2 as I’m using Y=0 by default). And zoom is the detail level.

Rest of it should be quite straight forward, I’m downloading and caching the JSON data. I believe there is already a WWW object with caching but I did it myself. This way it’ll be easier to chance database (text, xml, sql) whenever I want. So if we already have the data for that tile, it’ll re-use the old data file. If not, it’ll just download the data from the mapzen server.
I also used a third party library to parse JSON in C# (see JSONObject above). It’s nothing fancy really, just parses the data and creates something like a nested dictionary for it, which simplifies searching stuff.

And finally we have two big function calls; CreateBuildings and CreateRoads, taking related JSON sections, mapData[“buildings”] and mapData[“roads”], respectively. You can find those sections in the map Json and again, for your own sanity, use a JSON formatter.

Now let’s have a look at the CreateBuilding function;

private void CreateBuildings(JSONObject mapData)
	foreach (var geo in mapData["features"].list.Where(x => x["geometry"]["type"].str == "Polygon"))
		var l = new List<Vector3>();
		for (int i = 0; i < geo["geometry"]["coordinates"][0].list.Count - 1; i++)
			var c = geo["geometry"]["coordinates"][0].list[i];
			var bm = GM.LatLonToMeters(c[1].f, c[0].f);
			var pm = new Vector2(bm.x -, bm.y -;

			var center = l.Aggregate((acc, cur) => acc + cur) / l.Count;
			if (!BuildingDictionary.ContainsKey(center))
				var bh = new BuildingHolder(center, l);
				for (int i = 0; i < l.Count; i++)
					l[i] = l[i] - bh.Center;
				BuildingDictionary.Add(center, bh);

				var m = bh.CreateModel(); = "building";
				m.transform.parent = this.transform;
				m.transform.localPosition = center;
		catch (Exception ex)

This is rather straight forward actually. I read vertex data for each building from the json object and create a mesh using those vertices using BuildingHolder class. Vertex coordinates are in lat/long system originally so first I convert them to meters (GM.LatLonToMeters call), then I substract the tile center from that as I attach buildings to tiles as children. I keep buildings inside a dictionary using their center point as key which isn’t a good idea and might cause problems with complex polygons (when a big concave polygon surround a smaller one, their centers may overlap). It’s good enough for now but you should consider finding a better key for them.

Another thing to note is that building vertices are kept relative to their center as well. So vertice positions are relative to the building center and building position is relative to the tile center, it’s a nice and clear hierarchical system. And building meshes are created inside that BuildingHolder class which makes it extremely easy to switch visuals. i.e. if you want 3D polygons, all you would need is to change whatever is inside that class to add height and the rest of the code will work just the same.

private void CreateRoads(JSONObject mapData)
	foreach (var geo in mapData["features"].list)
		var l = new List<Vector3>();

		for (int i = 0; i < geo["geometry"]["coordinates"].list.Count; i++)
			var c = geo["geometry"]["coordinates"][i];
			var bm = GM.LatLonToMeters(c[1].f, c[0].f);
			var pm = new Vector2(bm.x -, bm.y -;

		var m = new GameObject("road").AddComponent<RoadPolygon>();
		m.transform.parent = this.transform;
			m.Initialize(geo["id"].str, this, l, geo["properties"]["kind"].str);
		catch (Exception ex)

CreateRoads is pretty much the same. Only different is taht I’m not generating polygons for the roads, just some debug lines so there is no mesh generation inside the RoadPolygon component. I’m just giving it the road vertices and it’ll draw lines between them in its update function.

You can find the project files below and there are a lot more than what’s covered here. Please do let me know if you have any questions or find any bugs/mistakes. I’m planning to write a few more blog posts on this, i.e. I already created a dynamic tiling system, which loads tiles as you move so you can travel all the way across usa or europe. Writing that was much easier than writing this blog post though, I’m having quite hard time writing in english so it may take some time :)

Anyway, let me know what you think!

UnityOsm.unitypackage (19.27 kb)

Read More

Random Planet Generator

So me and my collague found this brilliant blog post; Procedural Planet Generation by Andy Gainey a few days ago. Even though it looks beautiful and stuff, it’s written in javascript which isn’t a popular development platform here, so we decided to convert it to C# & Unity3D.

We’ve only done the icosahedron subdivision part for now, but still working on the rest actively.



You can find the Unity3D project files below but beware, it’s just a raw translation from Javascript to C# at the moment and looks quite ugly (I mean the coding style). I’ll do the refactoring and beautifying stuff when we’re done with it. That being said, we may not do a 100% conversion either and go on a different way at some point.

Anyway, I hope you guys find it useful, please do notify us about any bugs or issues in the C# version so we can fix it asap. Enjoy!

Read More

bTube – 2D Texture Shader

Before I start, I must say that I know nothing about shaders at all and I managed to get this together googling & asking my friends all the way. So I’m hardly a reliable source on this topic but still thought it’s worth sharing so here we go…

If you played bTube, you must have noticed that something looks off with the incoming barriers. I mean can you even tell if they are 2D or 3D? Have a quick look if you want; bTube.

As you can see, those 2D looking slices are actually just 3D objects with a special shader that fixed their textures to 2D world. Well why did I made it in 3D then? That’s a whole another question and I can shortly say it felt easier at that time. And with this shader it’s quite hard to tell the difference anyway.

So what does this shader do? It applies the given texture in 2D screen coordinates instead of the 3D triangles. I know I’m quite horrible at describing things like these in words so just check this, yet another comparison image below;


Left, is the standard diffuse shader, applying texture to triangles in 3D coordinate system. Right is the shader I used, which doesn’t even take vertex positions into calculation, just slaps the given texture on the screen as a 2D image with no depth.

So it’s an extremely cheap & easy trick but I still believe it’s quite underused and can generate awesome effects ( as seen in bTube! ). You can find a simpler version of what I used in game below. Only difference is I used a color as multiplier for the “space effect” in bTube. Thought it was irrelevant here so took it out for this blog post.


Shader "Custom/FixedTexture" {
 Properties {
	_MainTex ("Texture", 2D) = "white" {}

SubShader {
	Tags {
	 "Queue" = "Geometry"
	LOD 100
	Pass {
		 ZWrite On  
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"
			sampler2D _MainTex;
			float4 _MainTex_ST;

			struct v2f {
				float4 pos : SV_POSITION;
				float4 screenPos : TEXCOORD0;
			v2f vert (appdata_base v)
				v2f o;
				o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
				o.screenPos.xyw = o.pos.xyw;
				return o;
			half4 frag (v2f i) : COLOR
				float2 screenUV = i.screenPos.xy / i.screenPos.w;
				screenUV *= _MainTex_ST.xy;
				half4 texcol = tex2D (_MainTex, screenUV);
				return texcol;


FixedTexture.shader (849.00 bytes)

Please do let me know if you have any questions!

Read More


Yeap, so I finished my first “One Game a Month” game, bTube, a few days ago.

It’s still far from done and have serious balance issues but still, if you want to try it out;

Please do let me know what you think!


Read More

Banner Saga Caravan Movement

So I’ve been playing Banner Saga for a few days.
I found the gameplay to be rather boring and underwhelming but as a winter person I kept playing just for the winter/snow scenes.
Brilliant art, good writing, great scenes etc.

One of my favorite things for me was the caravan scenes,

Doesn’t that looks BEAUTIFUL?
Yea they put such awesome scenes in between the fights to keep player going and it totally worked on me.

Anyway, so I decided to do that myself in Unity, as I always do. I manage to… recreate it somehow. Sadly programmer art is nowhere close to what you’ve seen above.


But it works and that’s satisfying enough for me. It’s just bunch of boxes moving on bezier curve really, nothing complicated.It also has a n-layer background, all infinite, generated as caravan moves etc.
I’m still not that comfortable with Unity but I think the overall structure is rather decent and flexible.

You can also check it out here;

Anyway you can find the project below,Let me know if you have any questions or whatever. ( )
I hope you like it, cheers!


Read More

Voronoi in Unity

Hey there!

Well I’ll keep this one short. I just got bored last week and decided to play with unity a bit.
I had the idea of converting my map generator stuff into Unity for a long time now but never had chance/time to do so.
And yea started with Voronoi stuff. Turns out that my old code is a horrible nightmare so rewritten most of the stuff, fixed some serious bugs etc etc.


Anyway, you can find the Unity Solution below.
And let me know if you have any questions!

PS: Yea I don’t know how to package Unity projects so I just zipped the whole thing. Please do let me know if there is a proper way. (310.96 kb)

Read More

Hexagons in Unity – Part 2

OK I decided to write a small post about that part where we create the vertices, UV coordinates etc in the previous post.
I’ll try to make it clear for the people who’re new in 3D stuff.


So yeah, we created a hexagon in our previous post, by creating every vertex and triangle by hand, instead of using a pre-build 3D model. For the simplicity, I’ll do a basic version of our hex this time and create only the top face of the hexagon. If you remember the previous post, it had a height, sides and a bottom etc.

Anyway, first have a look at this;

Our hex has a radius of r, this is the distance from the center to any corner. In a standard hex, this is also equals to the edge length. And we have “Half Width”, well it’s the width divided by two really. Nothing fancy.
Remember that we’ll be using center of the hexagon as origin for creating the vertices. So for example, the coordinates for the top corner should be; ( 0, -R ).

UV mapping is a little bit different though. First of all, origin for UV mapping is always bottom left corner, this is fixed and you really can’t change it. Also the width and height of the UV map is scaled down to 1 ( see blue coordinates in the picture ). So again, UV coordinates for the top corner should be; ( 0.5, 1 ).

Let’s have a look at the function;

Vertices[0] =new Vector3(0, 0, Globals.Radius);
UV[0] =new Vector2(0.5f, 1);
Vertices[1] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[1] =new Vector2(1, 0.75f);
Vertices[2] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[2] =new Vector2(1, 0.25f);
Vertices[3] =new Vector3(0, 0, Globals.Radius);
UV[3] =new Vector2(0.5f, 0);
Vertices[4] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[4] =new Vector2(0, 0.25f);
Vertices[5] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[5] =new Vector2(0, 0.75f);


Array indexing for these stuff is actually important so be careful with that. Other than that, yea I guess that’s all for this one right?

So now we have bunch of vertices in the space but that doesn’t mean much in a 3D world. To create something visible, we need surfaces and for that we need triangles. Next thing we need to do is to set the triangle information, in other words, let the system know which 3 vertices will be used for a triangle.


Now check this out;



Notice that numbers right by the corners are the index numbers of vertices in the Vertices array. So now we divided our hexagon into 4 triangles and all we have to do is;


Triangles =new int[]
1, 0, 5, 2, 4, 3, 2, 1, 4, 1, 5, 4

This array will take integer three by three and generate triangles out of them. So 1,0,5 will be our first triangle, 2,4,3 will be the second etc.
Important thing to note here is that, order of the vertices do matter. In our situation, we ordered them counter clockwise so the surface will be above ( it’s all one sided ). If we had them clockwise, surface would have been below. So if you want to turn it over, you can just change the order of vertices, ie 1,0,5 to 1,5,0.


There is one more little thing in the code I posted earlier; Normals.
Normals aren’t always necessary ( depending on the shader ) but it’s good to know really. They are small vectors, showing UP for every single vertex. Yea, Up as in the opposite of down. Normals are used for lighting calculations so pretty damn important as well. For this example though, our normals array will be extremely simple as our shape is simple itself. It’s a simple surface so we can just set all vertex normals to 0,1,0 ( world up in my sample ).


Normals =new Vector3[]
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0)

Again the indexes should be in sync with other array indexes, so first vector3 is the normal for vertex 0 etc.

Aaaand that should be it. You can find the whole sample code in the previous post.

Let me know if you have any question, liked the post or wanted to say hi.
I had to close the comments due to increasing spams but you sure can always mail me for anything;
See you later everyone!

Read More

Hexagons in Unity

OK so it has been ages since I last posted something useful here, I’m a bit rusty and my aged post editor is torturing me, but I’ll do my best.

Let’s talk a little bit more about Unity and Hexagons.
Why? Well pretty much because both are the coolest things in their fields.
Unity is just stupefyingly easy and fun. Likewise for hexagons, they are incredibly sexy as well. So yeah, Unity & Hexagons.

I’ll assume that you’ll know the basics here, like creating a script etc. Oh and that being said, I’m a rather newbie in Unity as well so my way of doing things may be wrong or (most likely) not optimal. I work in XNA-ish way a lot and pretty much refuse to learn Unity practices etc. I may be so totally wrong on doing that but yea, that’s how it is for now.

Anyway, let’s get started;

In this post, we’ll create a simple hexagon for future usage. We’ll create it vertex by vertex, not using a 3D model or anything. Most important point here is to make it flexible and manageable for future projects. This is pretty much what we’re trying to achieve in the end ( first pic );

First of all let’s create a Hierarchy like in that second pic above.

Nothing fancy there really as we’ll create everything in code. Told you I don’t like drag&drop stuff and I’ll do it all xna style.
World and HexHolder are empty game object, that’s pretty much it.

Now as another easy step, let’s create a simple script for “Hex”;



Once again, nothing fancy.
Two things to note here;

(1) is that I added a public Vector2 HexPosition to the Hex script. This is not the x,y,z coordinates of our hexagon. This is the location of any particular hex on the base hex grid ( see that final pic above, whole surface is a big huge grid that doesn’t exists in code but does theoretically ).

The grid we’ll be using is something like this; ( indexing may be different though, I just googled this picture )

(2), we have another object, HexModel inside this one. What’s that? That’s all the vertices, edges and whatever of our Hex. Pretty much the physical or visual stuff wrapped all together. All that stuff gets extremely hairy so I just created a sub class for them.

Speaking of the model, let’s look at how we create that one;

This InitializeModel function actually is inside Hex class. Why? Well mainly because I wasn’t able to find a useful constructor implementation for components. So instead, after setting some important values, I call model creator myself. We’ll look into that later on.

So first, we created a new game object and added that new component HexModel to that. We keep the component reference in Hex, not the game object ( not a big difference but saves us some calls ). Then we set hex parent to be current object’s transform.
This will make HexModel a subobject to Hex in the game hierarchy.
Setting position to zero as it’s relative to the Hex and we want them both at the same place ( for now ) for obvious reasons.
Shader is just a standard share, I’ll add that to files but won’t talk about it here.
And texture is just a filler texture, nothing special.

So where are we standing now?
We have a world hierarchy, a hex wrapper “Hex” and a model “HexModel”.
Well we actually haven’t created the HexModel yet so let’s do that now.

Add a new script inside the assets as normal and open it with whatever IDE you’re using BUT this time we’ll make a vital change/addition to the script file;

Notice the new line right above the class definition. That lines says, this component requires a MeshFilter and MeshRenderer in whatever object it’s attached to. In other words, this script can only be attached to physical objects ( with mesh stuff ).

First property is just optional, I always like to keep a reference to parent object if possible.
Then, since this will be a mesh object, there are some stuff we have to have for visualization, like Vertices, normals etc.
The idea is to set all these vertices, normals, UV and let Unity draw them on screen.

void Start ()
Parent = transform.parent.GetComponent<Hex>();
Vertices =newVector3[24];
UV =newVector2[24];


var mesh =newMesh { name =“Hex Mesh” };
GetComponent<MeshFilter>().mesh = mesh;
mesh.vertices = Vertices;
mesh.uv = UV;
mesh.triangles = Triangles;
mesh.normals = Normals;

I don’t even know why I’ve been posting pics, not embedded code really. Anyway here it is, should be easier now.
This is the start function of HexModel. First we get and save a reference for the parent objects Hex script, then we create arrays for vertices and UV.
Next 3 functions creates vertices, they are extremely straight forward and simple, not sure if there is anything to talk about them. I might do another post in the future but I’ll skip them for now. They’ll of course be in the sample solution below.
And 3rd part is, now that we set vertices and UV’s, we tell Unity to use them as this current game objects mesh.


Now two important things,
First we’ll create a few global variable for our hexagon grid, like hex radius and related values.
Simply create a new C# script file and paste all this into that;

using System;

public static class Globals
public static int Radius =8;
public static int Height =2* Radius;
public static float RowHeight =1.5f* Radius;
public static float HalfWidth = (float)Math.Sqrt((Radius * Radius) ((Radius /2) * (Radius /2)));
public static float Width =2* HalfWidth;
public static float ExtraHeight = Height RowHeight;
public static float Edge = RowHeight ExtraHeight;

Those are some generic values all calculated using base radius value. I don’t like static stuff for obvious reasons but I feel like this is OK and since it makes everything much easier… yeah.

And now we’ll create the script that’ll run first and create everything. Remember that “World” object we created in game hierarchy? Yeah we’ll use that as script host for this, so create a “World” script and attach it to the World object.

publicclassWorld : MonoBehaviour {

Dictionary<Vector2, Hex> Hexes { get; set; }

void Start ()
Hexes =newDictionary<Vector2, Hex>();

var position =newVector2(0,0);
var pos = ToPixel(position);

var hex =newGameObject();
var hm = hex.GetComponent<Hex>();
hm.HexPosition = position;
hex.transform.position = pos;
hex.transform.parent = transform.FindChild(“HexHolder”);
this.Hexes.Add(position, hm);

In our “World” we just have one single dictionary for now, which will help us to keep track of all hexagons we have in this world.
Then we’re creating a new hexagon at grid position 0,0. Remember this is grid position, not global x,y,z of the hexagon.
We send that grid position to a function to convert it to exact pixel coordinates, that’s the function I posted long ago in another post. Won’t go into that here as it is long and boring but it’s there in the code if you want to check it out.

It’s standard stuff really, we create a new game object, attach our Hex script to it. Set it’s HexPosition, set it’s pixel position, added it under the “HexHolder” object we created at the begining ( parent-child relation here, just to keep stuff organized ). Then we call InitializeModel function which will create the flesh and bones of our hex and add it to the list for future references.

Well we’re pretty much done, just one little thing, do no forget to add “Resources/Textures/” folder into assets and create a “Hex” texture there. Our HexModel will look for it and if it’s not able to find it, it’ll look all dark grayish.

At this point, if you run it on Unity and play with the camera angles a little bit, you should get something that looks like this;

Well it’s not the worlds most beautiful hexagon but it’s 100% your!
You can add lighting and whatever to make it look better really,

Yeah I guess a little bit better.

You can find the whole sample here; (176.86 kb)

For some reason it won’t load the scene by itself though, remember to load the scene yourself after opening the project ( file -> open scene -> hexagons ).

Anyway, let me know if you have any question, liked the post or wanted to say hi.
I had to close the comments due to increasing spams but you sure can always mail me for anything;
See you later everyone!

Read More


Soooo it has been a while eh?

I know I know, I really should start posting again. It’s not that I’m not doing but I’m terribly busy and doing some oh-not-so-cool stuff these days. ie. master course homeworks -_-

Yeah, boring days, development wise.

Anyway, I had little free time yesterday and decided to check out Unity3D. I actually was looking for a chance to check it out for… a few years now? Finally yesterday was the day!

My first experimental work was on hexagons as usual. I just love hexagons.

I learned a decent amount of stuff about code management and structure of unity. It’s quite fun really, even felt a little bit toooo easy haha.

Even after switching from XNA to Unity, I’m still creating every object vertex by vertex by the way, not sure if it’s a good habit or not but sure feels weird.

Anyway you can check it out here; ( WASD for movement and mouse for camera )

Oh yea I’m also LOVING this web player thing. A few seconds of gameplay is sooo much better than thousands of screenshots afterall.

I’ll try to post more and especially about Unity in the future.


Read More

Robotics & Voronoi

So my 3rd homework in Robot Motion Planning class was about voronoi diagrams. Nice isn’t it?


It’s about generating a voronoi diagram of environment so that robot can move safely as that diagram using it as a roadmap. Neat idea actually, surely not the best and somewhat cumbersome but still good one.

But the diagram generation technique was different this time, we were supposed to create the diagram by walking on it while keeping the distances in balance etc etc.


Anyway the paper is here, not my best work but it’s there anyway so it could be on my blog as well right?


Read More