- Home /
SOLVED: Calculate sphere UV from position (without discontinuity)
SOLVED: Read my post below for the solution. It was a simple mip mapping issue (caused by the discontinuity, but not where I expected to find the issue).
I need to calculate the UV coordinates from the world position, which I use to sample a temperature map texture to add snow to the terrain. I used the Atan2 formula described multiple places, including Wikipedia, but the discontinuity along the -x axis (approaches pi from one side an -pi from the other) leads to a pixel wide error region.
Here is the shader code:
float2 UV = float2( saturate(((atan2(position.z, position.x) / pi) + 1.0) / 2.0), (0.5-(asin(position.y)/pi)) );
And here is the C# version used elsewhere (including calculating the mesh.uv):
Vector3 d = position.normalized;
float u = Mathf.Clamp01((Mathf.Atan2(d.z, d.x) / (Mathf.PI) + 1f) * .5f);
float v = 0.5f - Mathf.Asin(d.y) / Mathf.PI;
I can't use the mesh UV, as it's used for both the terrain and objects. I realize that this is caused by the UV.x wrapping around from 1 back to 0, but as the texture wraps perfectly, forcing it to sample UV.x = 1 on one side and UV.x = 0 on the other side should still smoothly wrap. Any ideas on how to get around this discontinuity?
Here's a sample shader using this UV for anyone to play with and test. I made it in ShaderForge, but I can write up a non-SF example too. Position To UV Shader (Dropbox)
Planet pictured here for reference:
Answer by TheMasonX · Aug 18, 2015 at 11:14 AM
SOLVED: Joachim Holmer, the creator of Shader Forge, was kind enough to look into this for me, and found out that it was due to the GPU not being able to figure out what mip level to use along the seam. The solution to this is to manually set the mip level using tex2Dlod(), like this: tex2Dlod(_TemperatureMap,float4(TRANSFORM_TEX(UV, _TemperatureMap),0.0,mipLevel))
Your answer
![](https://koobas.hobune.stream/wayback/20220612000223im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
UV-ing a sphere procedurally 1 Answer
How do I go about texturing a flat-shaded generated mesh? 1 Answer
Water on a non-planar mesh 0 Answers
UV offset in surface shader. 1 Answer