mapbox-unity-sdk icon indicating copy to clipboard operation
mapbox-unity-sdk copied to clipboard

Convert between unity world space<—>earth space

Open wx0165927473 opened this issue 9 years ago • 30 comments

I already set up a static map with pre-setup lat and long. I want to point at one location on the map and convert the location to lat/long in earth space?

The game scene has a map object with abstract map and range tile provider scripts attached to it.

I tried conversions.metersToLatLon function which I passed the x and z of aim point (Unity world position I think) as parameters. However, the result is (-0.00031,-0.00006) kind of data.

What else I need to do in order to get real lat/long from the map where I am pointing at.

Thanks.

wx0165927473 avatar Jun 15 '17 00:06 wx0165927473

You could maybe look into the GetGeoPosition methods in VectorExtensions.cs.

I have this line of code in my tile provider: _currentPlayerGeoLocation = _playerTransform.GetGeoPosition(_map.CenterMercator, _map.WorldRelativeScale);

So you could probably do this on a Vector3 as well, something like: Vector3 geoloc = new Vector3(0, 0, 0).GetGeoPosition(_map.CenterMercator, _map.WorldRelativeScale);

_map is just a reference to my AbstractMap implementation in the scene.

Alexphauge avatar Jun 15 '17 07:06 Alexphauge

@wx0165927473 I tried conversions.metersToLatLon function which I passed the x and z of aim point (Unity world position I think) as parameters. However, the result is (-0.00031,-0.00006) kind of data.

You should add CenterMercator (under abstract map) to your x&z values. You'll get a better result but you'll also have to multiply x&z by WorldRelativeScale to get the correct lat/lng. So it should be; CenterMercator + (yourPos*WorldRelativeScale) This gives your position in meters (on mercator projection), then you can use metersToLatLon. As @Alexphauge suggested, GetGeoPosition will work as well. It's doing the exact same thing really. So you can do; yourPos.GetGeoPosition(CenterMercator , WorldRelativeScale)

brnkhy avatar Jun 15 '17 10:06 brnkhy

@wx0165927473 Please let us know if this solves your problem (or feel free to close the issue if resolved). Cheers!

david-rhodes avatar Jun 16 '17 19:06 david-rhodes

@brnkhy It works. Thanks.

wx0165927473 avatar Jun 16 '17 19:06 wx0165927473

I am also trying to position game object in the world based up their lat, lon, and elevation. However, they are off and I can not determine why. I am using the following:

Vector3 loc = Conversions.GeoToWorldPosition( latLonV2d, _map.CenterMercator, _map.WorldRelativeScale ).ToVector3xz(); loc = new Vector3( loc.x, elevationMetersMSL, loc.z );

Can you give more insight into how map.WorldRelativeScale and/or map.Zoom determine the coordinate system of the map model in Unity?

What is the units along the Y axis that matches up with the terrain elevations. My assumption was that it is in meters MSL but the models fit onto the elevation with that assumption. Should the Y axis value also be scaled by map.WorldRelativeScale?

My question is an extension of this issue so I hope it is proper to put it here.

derekdominoes avatar Jun 17 '17 13:06 derekdominoes

Hey @derekdominoes ! Actually yes it would be better trying to explain it properly. We're actually using 1-1 scale between real world meter (on mercator projection) and Unity units. So one unit is exactly 1 meter. Everything in mesh generation system functions like this.

But of course this causes lots of troubles, especially with huge terrains and low zoom levels (i.e. you load whole asia). It get way too big to be usable and even reaches floating precision max point at some level. So we need some sort of scaling and instead of embedding this scaling into every single calculation in mesh generation, we simply scale down/up the whole world to keep it in a fixed size (AbstractMap._unityTileSize).

So no matter how big/small your world is, it scaled so that one tile width/height will be equal to exactly _unityTileSize value. This is where it creates some confusion though. So for example you have a point in a tile and you want to put a prefab there. Since that point is already in the tile (relative to tile), you can simply create the prefab as a child of that tile and root object scaling will be applied automatically and your prefab (with position relative to tile center applied) will be exactly where you want. So two important points; -set tile as parent -set position relative to that tiles center

But let's say you have lat/lng and you want to create a prefab on that coordinates and it won't be a child of a tile or anything. When you convert that lat/lng to meter directly, you'll get a huge number because that position is actually relative to the mercator world origin (somewhere close to west africa coast). Now we substract our own maps center position from that. This new value will be relative to the unity space origin so we're almost there. But we scaled the whole map down right? If we didn't, that number would have been enough. With map being scaled down, you have to apply same scale to that number as well so it'll have the same meter/unit ratio with the rest of you world. SO you multiply that value with world scale and that's the correct point to place your prefab. So; -convert to meter -substract map center to make it relative to that -scale this new value by the same factor you scaled your map

Hope this helps!

brnkhy avatar Jun 17 '17 18:06 brnkhy

I would have never got that right. But maybe I still don't get what you mean. I tried the following but it is still not positioning things correctly, let alone getting the height right: Vector2d worldPos = Conversions.GeoToWorldPosition( latLon, _map.CenterMercator, _map.WorldRelativeScale ); worldPos -= _map.CenterMercator; worldPos *= _map.WorldRelativeScale; Vector3 toPlaceOjbect = new Vector3( (float)worldPos.x, heightInMetersMSL * _map.WorldRelativeScale, (float)worldPos.y ); Can you tell met what I'm doing wrong or provide a snippet that will turn a lat, lon, altitude into the position in the Unity world coordinate system? I'd appreciate the help.

derekdominoes avatar Jun 18 '17 15:06 derekdominoes

@derekdominoes isn't just that first line/conversion enough? have you tried with just that? Because it's doing all others inside it.

brnkhy avatar Jun 18 '17 15:06 brnkhy

That's what I started with. But it is off in all positions: image The red runway is out of place and I had to raise it manually 460 units to get it above ground level. The Unity Tile Size is 1000 and the Zoom is 13.

derekdominoes avatar Jun 18 '17 16:06 derekdominoes

This is me just adding the runway object creation code to the releases MeshGenerationOnTerrain example. I confirmed my coordinate in Google Maps. Scale looks correct

derekdominoes avatar Jun 18 '17 16:06 derekdominoes

@derekdominoes first of all, this calculations won't handle y axis no matter what so that's normal and you'll have to do the terrian snapping separately yourself. Second, actually if you had a calculation error, you would have ended with a much worse result. This is rather close so I suspect there's something else wrong in there. Can you give me the lat/lng you're using for map and runway coordinates you're using? Not much I can say without testing it myself I guess.

brnkhy avatar Jun 18 '17 19:06 brnkhy

Yes, I agree the closeness makes it odd. Sure... Abstract map is at 40.0391, -105.233 and the centerline of the runway is Vector2d( 40.0391f, -105.233f ) and Vector2d( 40.0391f, -105.219f )

In order to use this library, elevation is critical. I am tracking flying vehicles. Positioning vertically can not be done with "snapping" to terrain. Are you telling me that the terrains surfaces are not positioned correctly in a Unity 3d world space vertically so that there is an accurate coordinate system to position against relative to the terrain?

derekdominoes avatar Jun 19 '17 00:06 derekdominoes

@derekdominoes I can help investigate this problem, but first can you please check that your MapRoot object is at world origin (0, 0, 0)?

david-rhodes avatar Jun 19 '17 17:06 david-rhodes

Yes it is. I never touch it.

derekdominoes avatar Jun 20 '17 00:06 derekdominoes

@derekdominoes this is what I'm getting for those coordinates, looks much better than your shot so it's probably something different in your case. unity_2017-06-20_16-16-28

This is the script I used;

public class AddPoi : MonoBehaviour
{
	public AbstractMap Map;
	public List<string> Coordinates;

	void Start()
	{
		Map.OnInitialized += () =>
		{
			foreach (var item in Coordinates)
			{
				var latLonSplit = item.Split(',');
				var llpos = new Vector2d(double.Parse(latLonSplit[0]), double.Parse(latLonSplit[1]));
				var pos = Conversions.GeoToWorldPosition(llpos, Map.CenterMercator, Map.WorldRelativeScale);
				var gg = GameObject.CreatePrimitive(PrimitiveType.Sphere);
				gg.transform.position = new Vector3((float)pos.x, 0, (float)pos.y);
			}
		};
	}
}

brnkhy avatar Jun 20 '17 13:06 brnkhy

And this is in z13 actually, first one was 15 or 16 I believe unity_2017-06-20_16-22-01

brnkhy avatar Jun 20 '17 13:06 brnkhy

@derekdominoes what I meant by terrain snapping is that you won't get height information from lat/long and you'll need another way to calculate y axis value. There are a bunch of ways to do this, and most precise would be querying our terrain height data as we're doing for all buildings and stuff ourselves. (another way is raycasting to the terrain mesh). Admittedly, I haven't had chance to test our height for that level of precision (it's also effected by latitude by the way) so this might be a good test, please do let us know if you notice anything.

brnkhy avatar Jun 20 '17 13:06 brnkhy

I had two errors. One in the geometry creation of my runway .and another in the fact that these two statements produce different results: new Vector2d( 40.0391f, -105.233f ) new Vector2d( 40.0391, -105.233 ) The runway is now properly located and scaled.

Elevation on the other hand is way off. The west end of the runway is at 5287ft or 1612m. Yet the terrain data says it is 2043! What coordinate system is the terrain data in? The ray trace hitpoint.position.y is approximate 43. Multiplying by map.WorldRelativeScale produces results < 1. What is the conversion to get any reasonable vertical coordinate?

derekdominoes avatar Jun 21 '17 12:06 derekdominoes

Hey @derekdominoes, I tested this again, as you noted it's approx 43 at unity world and when you divide that by the world scale of 0.02044, you get something around 2076 which is close to the figure you got from data BUT far from the correct one. Investigate the issue a little bit, admittedly I was expecting some error due to latitude effect on y-axis but I think I found it and looks like a small mistake; In UnityTile.cs line 169; we pre-calculate the heights and store it in an array and line goes like this; _heightData[xx * 256 + yy] = Conversions.GetAbsoluteHeightFromColor(r, g, b) * _relativeScale * heightMultiplier; The problem is, this value is supposed to be real world height and scaling is applied to this by root object scale in the end, so if you remove that relative scale from that line; _heightData[xx * 256 + yy] = Conversions.GetAbsoluteHeightFromColor(r, g, b) * heightMultiplier; This one gave me 1602m for the first (top left pixel) so rather close and probably the correct figure.

Edit: oh and for the maximum precision, I highly suggest increasing terrain resolution as much as you can. Higher res = more sampling

brnkhy avatar Jun 21 '17 13:06 brnkhy

I reopened this issue. You can find the PR fixing height at; https://github.com/mapbox/mapbox-unity-sdk/pull/132 will be merged after testing in different locations.

brnkhy avatar Jun 21 '17 13:06 brnkhy