Mapbox in Unity 2018

Mapbox in Unity 2018

Learn how to set up Mapbox and how to script projects in this tutorial by Jesse Glover, the author of Unity 2018 Augmented Reality Projects.

Setting up Mapbox

1: The very first thing you need to do is sign up for Mapbox. This requires a username, email address, and password:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/038d8f20-bac0-4ac0-a86d-1b0720e9e096.png

2. After you have signed up and verified your email address, it will take you to a page to find out which version of Mapbox you need. You have the option of iOSAndroidWeb, and Unity:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/f98fd1c7-eadb-4754-94c3-9e8fdffbb298.png

3. Choose the Maps SDK for Unity, and ensure that you’ve downloaded the Unity package before proceeding:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/52bebdfe-7c65-4b1e-80f1-45404517b4f9.png

4. You’ll be given an access token, which will be required to utilize the Mapbox software. Make sure you copy this key and paste it into Notepad for later use:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/aad7e344-abef-453e-bc3c-cbefa1a6af21.png

5. Create a new Unity project and call it Fitness for Fun:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/415e4a25-015b-44fd-9774-80a7640a70c5.png

6. Import the Mapbox Unity asset file into the project:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/236899b2-f47b-4ac2-808c-823c3fe42996.png

7. This will probably take some time to install:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/78284daf-4787-470d-a3b6-b85fad9dd106.png

 

8. Right away, after the installation, you should notice a new menu item called Mapbox. This opens up quite a few new features that are exposed for us to play with:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/83898da6-ce50-47e4-9bde-b9dacd166eda.png

9. Mapbox gives us Atlas Template GeneratorClear File CacheSetup, and Map Editor options:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/4a267b4c-81eb-44d4-bedb-b282fae716ac.png

10. The Mapbox Atlas Template Generator is a tool that allows you to create and test custom map atlases:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/2d0ace9a-3a1d-4bb7-87af-63273051b086.png

11. The Map Editor allows you to visualize the underlying data structure of the maps you create and use:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/0ef9eee3-5272-4a38-ad25-60bfc711dd5a.png

12. In addition to that, the Map Editor’s data is tied directly to the Map object’s Abstract Map Script. Any changes you make to the Abstract Map Script data is reflected in the Map Editor, and any changes you make in the Map Editor are reflected in the Abstract Map Script’s data:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/1f490499-c0d5-49a5-bbc1-ab8bf9408e6e.png

13. The Mapbox Setup option allows you to select Example scenes or Map Prefabs; however, this can only be accessed after you copy and paste your Access Token and submit the information. This will require you to be connected to the internet for verification:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/b7b231cf-a32d-4b1b-9b4d-9cbec6aa88ca.png

Important items to note

With different project types, you will have prefabs that will automatically be added to the active scene. In this section, you will go over the main object that is added to any template type, which is the Map object.

The Map is the most important object that is added to any template and has many extremely important items within the script that you should go over:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/c2007f13-a247-4ee2-8e82-b084e17dacaf.png

 

The first item within the Map object is the Abstract Map script. The most important items within are MAP LAYERSGENERALLocation, and Others:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/4cf92c37-d2ee-4f3c-a83c-5fce90415da3.png

Within the GENERAL tab, you have:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/1bf14dd5-ff60-48f3-a15c-e0d42889daee.png

  • LatitudeLongitude: If you click on Search, you can set this by typing in an address, or country and city, or even city and state, depending on the location you want to utilize. It will automatically convert it to be latitude and longitude values.
  • Zoom: This is specifically set for how close and far away the map can be drawn; be advised that the zoom function will only work appropriately if you have the proper tilesets generated for it.
  • ExtentOptions: These are how far you want the map to be drawn. By default, it is set to the bounds of the camera.
  • Camera: This is the camera you want to use, whether it is an AR camera with Vuforia, ARCore, ARKit, or even the regular Unity camera.
  • UpdateInterval: This is how long the program should wait before updating positions and drawing.
  • InitializeOnStart: This is a Boolean value for whether or not you want the map to immediately be drawn upon the start of the scene:

The Others tab has a few options as well:

  • PlacementOptions allows you to choose between At Location Center and At Tile Center. This controls the center or root placement of the tiles. Location center can be defined by you whereas the tile center is the center of the tile.
  • Snap Map To Zero is a Boolean value that specifies whether or not the map’s root should be snapped to 0,0,0.
  • Scaling Options allows you to choose whether you want a custom or world scale. Custom is defined by Unity using a Mercator conversion factor. World scale means that the actual scale is rendered and the Mercator conversion is ignored.
  • Unity Tile Size is the size of the tiles used in Unity units.
  • Loading Texture is the texture used when the textures are loading.

The next tab is the IMAGE tab:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/da78efba-f198-42a9-a8cf-f9757efb57d8.png

  • DataSource: This is the source of maps. You can use Mapbox StreetsMapbox OutdoorsMapbox DarkMapbox LightMapbox SatelliteMapbox Satellite StreetCustom, or None. These are essentially theme options for the map you want to use.
  • UseRetina: This is a Boolean that allows you to choose whether you want to enable the usage of larger texture maps and better visual quality for retina displays.
  • UseCompression: This is a Boolean that allows you to use Unity compression for the tile texture.
  • UseMipMap: This is a Boolean that lets you choose whether to use Unity-generated mip mapping.

The next tab is TERRAIN, which gives you the ability to modify the terrain of your Mapbox maps:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/9f895aa5-9c29-4999-bc0f-08a86f7b44a0.png

  • Data Source: This is the first option available, and it lets you choose between using Mapbox TerrainCustom, or NoneMapbox Terrain provides you with digital elevation with worldwide coverage. Custom allows you to use a custom elevation model. None is a flat terrain.
  • Map Id: This is the ID of the corresponding tileset that you want to use.
  • Elevation Layer Type: This gives you the choice between Flat TerrainTerrain with ElevationLow Polygon Terrain, and Globe Terrain. This allows you to render your terrain with the specified elevation type. Flat Terrain renders a flat terrain with no elevation. Terrain with Elevation renders a terrain with elevation from the source specified. Low Polygon Terrain renders a low polygon terrain with elevation from the source specified. Globe Terrain renders a terrain with no elevation for a globe.
  • Base Material: This is the material used to render the terrain tiles.
  • Exaggeration Factor: This multiplies the factor to vertically exaggerate elevation on the terrain; however, it doesn’t work with the Flat Terrain Elevation Layer Type.
  • Add Collider: This is a Boolean that lets you add Unity physics colliders to terrain tiles for detecting collisions.

The Others tab within the TERRAIN tab has a few options available as well:

  • Sample Count: This gives you the resolution for your terrain, with the result being an n x n grid.
  • Use Relative Height: This is a Boolean that lets you use a world-relative scale for scaling the terrain height.
  • Earth Radius: This is the radius of the Earth you want to use in meters.
  • Show Sidewalls: This is a Boolean that adds side walls to terrain meshes, which reduces visual artifacts.
  • Add to Unity layer: This adds the terrain tiles to the Unity layer. Upon checking the checkbox, you will get the choice of which layer you want to add them to—DefaultTransparentFXIgnore RaycastWaterUIPostprocessing, and Add Layer.

Next is the MAP LAYERS tab:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/d1d55c44-b4f8-4d90-89fa-f41baad22cbd.png

  • DataSource: This is the source dataset for the vector data.
  • MapId: This is the ID of the map you’re using.
  • UseOptimizedStyle: This is a Boolean that allows you to use Mapbox-style optimized tilesets that remove any layers or features in the tile that’s not represented by a Mapbox style. Style-optimized vector tiles are smaller, serve over the wire, and are a great way to reduce the size of offline caches.
  • EnableCoroutines: This is a Boolean that allows you to use coroutines.
  • EntityPerCoroutine: This specifies how many entities can be grouped together in a single coroutine call.

POINTS OF INTEREST is the next tab. Here, you can create special markers for important locations in your application or game:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/01fee042-fc22-417b-8964-24440b075e07.png

  • RequiredMapId: This is the map ID of the tileset you are using and cannot be empty.
  • AddLayer: This allows you to add points of interest layers.
  • RemoveSelected: This allows you to delete a layer.

The last tab is FEATURES, which gives you Vector Layer Visualizers with the options to add or remove visualizers. FEATURES allow you to modify how certain features look in relation to the point of interest you create:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/f59bf9ca-7ce5-4762-ba8a-a5d9c9a6a846.png

  • AddVisualizer: This allows you to change how you visualize a points of interest layer
  • RemoveSelected: This allows you to delete the selected visualizer

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/0a0e48d5-0ac4-4cc4-bf96-5cda92d73496.png

Finally, you have another script called Initialize Map With Location Provider, which only has the option to add an Abstract Map object to it. This script does what the name states—it registers if you are on an iOS, Windows, or Android device, and selects the Location Provider that is most relevant to it.

Setting up the project

It's now time to set up the project:

1. Create a new scene and call it FitnessFun:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/e733b301-2d20-4df8-aa80-775a7143da38.png

2. Click on Mapbox and then Setup. This will open a setup menu where you need to paste your Access Token in order to gain access to the Map Prefabs template:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/9a63b597-45b8-4353-a8c4-61bd3dfd865a.png

3. The Map Prefabs template to use is Location Based Game:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/df571e07-1af2-420d-a4b2-117ddc6739d7.png

4. It will add a prefab onto your scene, which will have what looks like a pawn in the scene edit tab:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/cd89b86c-1a76-454d-b059-de0ed76b562b.png

5. If you look over in the Hierarchy pane, you’ll notice a LocationBasedGame prefab added there, and if you drill down to look at the objects inside, you’ll see a MapPlayer, and LocationProvider inside. You’ll also notice Canvas and EventSystem automatically added to the Hierarchy:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/9512c271-9baa-4172-95b2-b79f15f3bf32.png

6. Inside the Scenes folder, create a Scripts folder:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/87c702c6-de66-45f8-8515-f356a85b5044.png

7. Inside this Scripts folder, create a C# script called TargetLocationController:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/a2a8782f-3e71-46d7-9527-4e3635ee21e3.png

8. Create another script called DestroyTargetLocation:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/41cdea6b-d9d4-4938-bfe0-336f7e41df0d.png

9. Go back to the Hierarchy pane and make a copy of the Player component:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/87620025-9897-45e9-81a4-1121f8ec3fe1.png

10 Remove the Immediate Position and Rotation with Location scripts along with renaming it to targetLocation:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/3fc65d60-849f-4998-86ef-ce3faa2c666b.png

11. Inside the Scenes folder, create a folder called Prefabs:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/a711d786-6bae-4309-9d19-552b9869edb7.png

12. Drag and drop the TargetLocation object into the Prefabs folder:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/54d9d3bb-f935-4d5d-97a5-10dbc067d985.png

13. Navigate to the Scripts folder and open the TargetLocationController script.

You need to write a script to create a new instance of the TargetLocation object and to destroy the object when something happens.

Scripting the project

1. First emsure you utilize Unity Engine, as you need access to MonoBehaviour:

Code

using UnityEngine;

2. The public class will be called TargetLocationController, which is of the same name as the script file you named in the Unity Editor. You will also inherit from MonoBehaviour:

Code

public class TargetLocationController : MonoBehaviour
{

3. Create a public GameObject called targetObject so that you can drag and drop your prefab onto this object to set a reference to it:

Code

private GameObject targetObject;

4. Now create a Start() method at this point. You want to find the object in the project with the tag of targetLocation, as you’ll be creating it upon a touch event instantiating it:

Code

private void Start()
{
    targetObject = GameObject.FindGameObjectWithTag("targetLocation");
}

5. You’ll need to create a SetLocation method and instantiate a new raycast to utilize the touch event the way you want for reading finger presses on the screen:

Code

private void SetLocation()
{
RaycastHit hit = new RaycastHit();

6. Now loop through to check on your input via touch events:

Code

for (int i = 0; i < Input.touchCount; ++i)

7. Check to see if the touch count is greater than 0, and if your touch phase is moved:

Code

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{

8. Now, construct a ray from the current touch coordinates on the screen:

Code

Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);

9. You need to do a check to see if the raycast hits anything:

Code

if (Physics.Raycast(ray, out hit))

10. If the raycast hits something, then create a new instance of your prefab with the position based on your touch event:

Code

Instantiate(targetObject, new Vector3(Input.GetTouch(i).position.x, 4.23f, Input.GetTouch(i).position.y), Quaternion.identity);
}
}

11. In the Update() method, call the SetLocation script:

Code

private void Update()
{
SetLocation();
}
}

12. Now, you just need a simple collision check script to check if the player object collides with the targetlocation object. You want to destroy the targetLocation object if the player object collides with it.

13. Open the Destroy Target Location script.

14. You’ll need the UnityEngine namespace as usual, since you want to inherit from MonoBehaviour:

Code

using UnityEngine;
using System.Collections;

15. The name of the class is the same as the name you gave the C# script file and inherits from MonoBehaviour, so you can attach it to a game object in the Unity Editor:

Code

public class DestroyTargetLocation: MonoBehaviour
 {

16. Create an OnCollisionEnter method with the parameters of Collision col:

Code

void OnCollisionEnter (Collision col)
{

17. Do a simple if check to see if what you are colliding with is the targetLocation object via the object's tag name:

Code

if(col.gameObject.tag == "targetLocation")
{

18. If the simple if check returns true, then you must destroy the targetLocation object:

Code

Destroy(col.gameObject);
}
}
}

You now have everything you need to finalize the project.

Finalizing the project

1. Navigate back to the Unity Editor, attach the targetLocation script to the player object, and set the object to be the targetLocation object:

https://dz13w8afd47il.cloudfront.net/graphics/9781788838764/graphics/4b28223c-550b-40a2-99e0-23da99d4b8ec.png

2. Attach the DestroyTargetLocation script to the object called LocationBasedGame:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/a8448c04-2525-4507-9bc9-e43a9404a09d.png

3. Now you can click on File | Build:

https://d255esdrn735hr.cloudfront.net/graphics/9781788838764/graphics/2893fecd-dac5-4231-b751-d7037b92ae41.png

4. Set the project type for Android:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/0db54d23-885c-4e9d-9639-5f8140494b7c.png

5. Make sure the only scene added for building is the Chapter6 scene. If the scenes list is empty, click on Add Current Scene:

https://d1ldz4te4covpm.cloudfront.net/graphics/9781788838764/graphics/ddb1f29b-e509-4ac4-a83c-e8c585dac67c.png

6. Now, build the project and install it on your Android device to run the program.

That’s it. If you enjoyed this article and want to master AR game development in Unity 2018, check out Unity 2018 Augmented Reality Projects. The book takes a practical, project-based approach to teach the specifics of augmented reality development in Unity and helps you build four immersive and fun applications using ARKit, ARCore, and Vuforia.

0 Comments
Leave A Comment

Please login to post your valuable comments.

Join the newsletter

Get the latest vLemonn news first

share