Search Unity

Resolved Getting UV coordinates of a world projected texture

Discussion in 'Shaders' started by shanataru, Jul 17, 2020.

  1. shanataru

    shanataru

    Joined:
    Mar 4, 2019
    Posts:
    13
    Hello,
    is there a way to get UV coordinates of a texture that is mapped onto tiled planes by using world coordinates - see code below (for surface shader):

    Code (CSharp):
    1. float height = tex2D(_HeightMap, IN.worldPos.xz / 20.0f).r;
    I am using contact points (created on collisions) to create rays which will intersect the plane and I would like to change the texture at the point of the collision. However, because of the world projected texture, I cannot get to the right coordinates of the texture to modify it.

    I know one can get UV coordinates of a texture using Raycast.Hit and then extract the main UV using https://docs.unity3d.com/ScriptReference/RaycastHit-textureCoord.html

    Thank you in advance
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,555
    Code (CSharp):
    1. float u = (worldX % planeWidth) / planeWidth;
    2. float v = (worldZ % planeDepth) / planeDepth;
    That would work with positive worldX and worldZ assuming the first one was aligned to zero (i.e. if it's 50 wide, they start at 0, 50, 100, 150 etc.). It would take a little more effort to handle negative coordinates or allow for offsets etc. but that's probably the simplest way to determine a UV from a world position for a texture tiled in world space (afaik).
     
  3. shanataru

    shanataru

    Joined:
    Mar 4, 2019
    Posts:
    13
    Thank you for your quick reply, I managed to get it working :) ! I am using a simple modified modulo, which works for negative coordinates as well.
     
    adamgolden likes this.