unity3d mapzen pokemongo water layer

PokemonGo clone using Mapzen – Part 4: Water Layer

Welcome back to the fourth part; Water layer, Git page, bug fixes and more!

-First of all, I finally created a git page for our little PokemonGo clone! You can find the latest fixes and updates, file bug reports, post feature requests there. I’ll be using it extensively so have no worries or hesitations about post there as well.

-Then we have some bug fixes. Previous versions didn’t really work properly in different detail levels for example. New tiles positions were messed up as well. They should be all fixed up now but yea, didn’t had time to test it extensively so please do let me know if you stumble upon anything weird. You can also read commit logs for more, I’m trying to write everything down properly there.

-There is also a parameter for tile sizes now. As you may remember, tile sizes wasn’t controlled in previous versions which caused countless problems. i.e. Lvl16 tiles were 611 unit wide while Lvl14 tiles were 2446 unit wide. Now we have a “TileSize” property under the world script, scaling down/up everything to fit tiles into that width&height.

-Last but not least, we now have a working water layer! It was a little tricky as there are lots of “MultiPolygons” in the water layer but turns out it isn’t that hard after all. I just did some silly mistakes which confused for a while. It happens. Occasionally. Sometimes frequently. But yea, with that fixed, we have a quite smooth water layer now. I just put a simple blue polygon for water but you can put Unity3D water over that easily.

unity3d mapzen pokemongo water layer
Yes, that’s Istanbul for you! Looking good? Nope? Yeah….

Hmmm am I missing something? Well it’s all on Git now, you can check all commits and commit messages for more. You can also check GitHub Issues page for known issues as well. I’m actively adding stuff there as well.

And that’s it. I guess. Please do let me know what you think about it or have any questions. Your feedback is what keeps me going. And page hits, share it will you? Thanks!

Cheers,
Baran

Download PokemonGO Clone Part 4: Water Layer

lots of tile osm mapzen unity3d pokemongo

PokemonGo clone using Mapzen – Part 3: Dynamic Tile Loader

As you may know, we already created a basic tile loader , player character and 3D buildings in the first two posts. Now we’ll try something a little more different, a dynamic tile loader. Admittedly I had no idea what to call it, “dynamic” might not be the best word here but couldn’t come up with anything better (and I’m open to suggestions). But it’s something that loads tiles dynamically…. well no. Whatever.

So what’s the problem we’re trying to solve here again? Well, Basic Loader gave us a central tile and n other tiles around it depending on the range parameter. But that’s a (quite small) finite set of tiles and you will eventually run off the map if you run in the same direction for a while.

We’ll take the most straight forward way to solve this; extend the world as player character gets close to any edge. There are lots and lots of different ways to really. I mean, how to detect player is getting close to an edge, how to load tiles or how many tiles to load etc. They’ll all have different properties and side effects but I think I’ve chosen one of the simplest ways and will try to explain it in detail now.

Wait actually before that, let’s have a look what we’re trying to achieve;

2016-08-02_00-36-44
Looking good? So let’s start!

  1. Yea guess I’ll try to enumerate like this. Anyway we’ll start with just like basic loader actually, one central tile and n tiles around it. Let’s say n=1 for the simplicity now, which yields 9 tiles, right? Something like this; (8 is the center tile, 2,3,4,7,9,12,13,14 are direct neighbors or Range1 tiles)tiles for dynamic tile loader mapzen osm pokemongo unity3d
  2. We’re safe as long as the player character stays inside tile 8. But as soon as it gets out of the central tile, we calculate a tile movement vector representing the players movement between tiles. i.e. for 8 -> 7, movement vector will be Vector2(-1,0). for 8 -> 4 it’ll be Vector2(1,-1). (see GetMovementVector method)
    One little problem here is; y-axis of the Unity3d coordinate system (or let’s say the scene I’m using) and TMS tile system is opposite. In other words, (0,0) is bottom-left in Unity3D while it’s top-left in TMS system. (see GetMovementVector method)
  3. We’ll pull a little trick here.. but let’s do it like this, what happens if the player character moves in a direction for hours? It’s a big big world as the songs says eh? Position vectors (of player, tiles and buildings) will grow and grow which will cause lots of precision problems after a while (7 digit numbers).
    So once player character leaves central tile, we’ll assign new tile as the central tile and move it back to (0,0) with everything around it. Doing this, everything will be kept around (0,0) all the time (see Centralize method) and with everything moved in one frame, you’ll nothing absolutely nothing at all on screen!
  4. So now we have everything in the (0,0) again. Now we can create new tiles using the very same function we used for basic loader. Remember we had 8 as central tile and loaded other around that? When the player moves to Tile 7, it becomes the new central tile and we’ll load neighboring tiles 1,6,11. Simple eh?
  5. One last thing, we don’t want to end up with hundreds of tiles on screen right? This is totally up to you actually but I’ll just assume that ,tiles further away more than d (from central tile in manhattan distance) are unnecessary, and simply destroy them (see UnloadTiles function).
    lots of tile osm mapzen unity3d pokemongo

I guess that’s all for now, had a lot more to talk about but it was a long day and I’m very very exhausted at the moment. I hope it’s still readable, I’m not even sure what I’m doing at this point.

I’ll try to post something like a todo list soon, consist of possible improvements on this. Will also post it on Github as soon as possible.
Hope you like this little dynamic tile loader thingy,  let me know what you think!

Cheers,
Baran

PS: just one more “dynamic tile loader” so that my SEO helper will shut up about low density -_-

 

v1.0:  Download PokemonGO Clone Part 3: Dynamic Tile Loader

Edit: There is a bug with the tile colliders at the moment. It collides with the player character, preventing him to move. I’ll fix and reupload it asap but untill then, you can simply move tile collider (big cube in (0,0,0)) to another tile and change “Layer Collision Settings” to prevent it colliding with anything. I did it like that but turns out “Layer Collision Settings” or even layers aren’t included into unitypackages. I’ll (hopefully) fix it in a few hours.

02.08.2016 – v1.1: Download PokemonGO Clone Part 3: Dynamic Tile Loader
-Fixed central tile collider problem by replacing it with a Rect

Unity_2016-07-27_22-42-19

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,
Baran
Download PokemonGO Clone Part 2

mapzen

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());
    }
    else
    {
       var www = new WWW(url + tileurl + ".json");
       yield return www;

       var sr = File.CreateText(tilename);
       sr.Write(www.text);
       sr.Close();
       mapData = new JSONObject(www.text);
    }
    Rect = GM.TileBounds(realPos, zoom);
    CreateBuildings(mapData["buildings"]);
    CreateRoads(mapData["roads"]);
}

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);
			l.Add(pm.ToVector3xz());
		}

		try
		{
			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)
		{
			Debug.Log(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);
			l.Add(pm.ToVector3xz());
		}

		var m = new GameObject("road").AddComponent<RoadPolygon>();
		m.transform.parent = this.transform;
		try
		{
			m.Initialize(geo["id"].str, this, l, geo["properties"]["kind"].str);
		}
		catch (Exception ex)
		{
			Debug.Log(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!
Cheers!

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!

https://github.com/alprkskn/RandomPlanetGenerator

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 {
	 "RenderType"="Opaque" 
	 "Queue" = "Geometry"
	 }
	LOD 100
	
	Pass {
		 ZWrite On  
		CGPROGRAM
			
			#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;
			}
		ENDCG
	}
}

}

FixedTexture.shader (849.00 bytes)

Please do let me know if you have any questions!

bTube

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;

http://barankahyaoglu.com/ogam/btube/btube.html

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;
http://barankahyaoglu.com/unity/banner.html

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!

BannerSageTests

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
Cheers!

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)