PokemonGo clone using Mapzen – Part 2: 3D Buildings

In this second part, I added a player character and 3D buildings to our cute little PokemonGo clone!

It’ll be a short post really. I used the Ethan model from “Standard Assets” package. All I did was importing the package, simple as that. It works with WASD controls at the moment as that’s the easiest way to navigate during development process but I implement GPS coordinate based movement in the future as well.

3D buildings was even in the previous package actually. I somehow forgot it in there but the building heights was set to zero so it was quite hard to notice it. Anyway I fixed the bug and the code itself for better looking buildings. Just better, not beautiful… but we’ll get there, slowly. Generation code is quite straight forward but still I’ll try to explain shortly.

As you know from previous post; CreateMesh() function in the Building class takes the building corners as a List<Vector3> called verts. Those vectors (coming from Mapzen Api), or lets say the polygon generated from those vectors, gives us the base of the building. What I did was, to generate that polygon in the air and use it as a roof. Then for every edge in the roof, I created a side wall down to y=0 and viola!

PokemonGo - Player character and 3D Buildings

This yields quite simplistic, bare bone buildings as seen in PokemonGo. Should be enough for now but might give BuildR a chance in the future as well.

With character movement working, we have a new problem at hand; player can actually run to & fall off the map. We’ll fix that in the next post, by creating & loading new tiles dynamically as the player moves.

Hope you like it, Cheers,
Download PokemonGO Clone Part 2

PokemonGo clone using Mapzen – Part 1: Basics

So my last post from 2014 December kinda exploded after the PokemonGo craziness and I decided to fix&improve it further. I’ll try to make a little blog post series on this one, starting with fixing/refactoring the old sample and then moving further and adding character movement, dynamic tile loader etc etc. I’m planning to have a proper Go clone when I’m done.

I’ll keep the post short as it’s quite time-consuming for me to write these as I’m still not feeling that comfortable writing in english (it’ll get there) but I’ll try to explain what’s going on as much as I can. But before we start, especially if you haven’t seen the old post, OpenStreetMap in Unity3D, I suggest checking that out first. It’ll be much easier/clear after that.

So first of all, you can get it here; PokemonGo clone – Mapzen sample and I’ll try to explain going over that here. Now extract the package, open scene file “BasicLoader” and run it.

PokemonGo clone

You should get something like this. Well it’s looks kinda ugly yea, but we’ll go into technical stuff before eye candy.

There are two gameobjects in the scene,
First one is the camera, which is pretty much standard camera with just one script (StrateCam) attached. It’s a quite handy little Orbit / RTS cam script.
Second one is “World” and that’s where all the magic happens.

Actually World script is just an entry / interface script. There is no logic or anything behind it, it’s just a container and starting point for the real thing; “TileManager”.

TileManager is the script responsible for handling everything about TMS tiles. For now, it just loads and created tiles but in the future posts, we’ll do a lot more here, like dynamically loading/destroy tiles depending on player position etc.

Tile script does pretty much everything (that sounds quite wrong, I know. Might refactor that later). It loads the data (this should be a service, bad idea doing it here), creates tile and uses BuildingFactory and RoadFactory classes to create building and road meshes/gameobjects respectively. As I said I’ll probably do some refactoring here but it’s quite straight forward for now. Load Data, create tile, load map image if necessary, create buildings create roads.

BuildingFactory and RoadFactory, are two simple factories for creating meshes and gameobjects given json objects and a relative position (owner tile center). We’ll add extra stuff like, fancy building model construction or curvy roads here. There are also some temporary (read wrong) stuff in there like using the first corner of a building/road as a unique identifier. Yes it’s wrong but somehow I couldn’t get Mapzen id’s to work for me couldn’t get my json parser to parse id’s properly , I’ll look into that later on as well.

And that’s pretty much it! Quite simple for now but I’ll be adding much more soon. Character movement and dynamic tile handling should be next two big things.

Hope you guys like it, let me know if you have any questions or whatever (I’ll be playing PokemonGo around),
Cheers, Baran

Download PokemonGO Clone using Mapzen Api Project




OpenStreetMap in Unity3D

Edit: New Post PokemonGO – Mapzen Post (26.07.2016)

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 OpenStreetMap 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;

unity3d mapzen OpenStreetMap

On the left, you can see the original OpenStreetMap 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 OpenStreetMap 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 OpenStreetMap . It’s a must-have tool if you’re planning to use OpenStreetMap 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. http://jsonviewer.stack.hu/).

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 = "http://vector.mapzen.com/osm/water,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 - Rect.center.x, bm.y - Rect.center.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();
				m.name = "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 - Rect.center.x, bm.y - Rect.center.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)

New Post PokemonGO – Mapzen Post
New Updated version (25/07/2016)

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!


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!


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!
E-Mail: brnkahyaoglu@gmail.com


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. ( brnkahyaoglu@gmail.com )
I hope you like it, cheers!


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! brnkahyaoglu@gmail.com

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.

MapGen.zip (310.96 kb)

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; brnkahyaoglu@gmail.com
See you later everyone!

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;
Hexagons.zip (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; brnkahyaoglu@gmail.com
See you later everyone!