Heyo,
I have two objects: a cube and a plane. They both have shaders that are being fed the same height map as a texture, and doing some vertex-height manipulations based on it. The plane is about 100 times the size of the cube, and the cube will always be located somewhere within the bounds of the plane’s x and z coordinates, and at the same static y coordinate. In the cube’s shader, I’d like to do a texture lookup using the texcoords of the plane at the cube’s position, so that the cube and the plane are always manipulated in the same way at any given position. So the question is, what’s the best way to do a texture lookup on the uv’s of another mesh? Or is there a better way to get them to the same height that I’m not seeing?
To help explain, here’s the basic code for the vertex shader:
vertexOutput vert (vertexInput i) {
vertexOutput o;
float4 worldPos = mul(_Object2World, i.vertex);
worldPos.y += (tex2D(_HeightMap, i.texcoord)).b;
i.vertex = mul(_World2Object, worldPos);
o.vertex = mul(UNITY_MATRIX_MVP, i.vertex);
o.texcoord = i.texcoord;
o.color = i.color * _Color;
o.normal = i.normal;
return o;
}
So essentially I just want line 4 of the above code to use the plane’s texcoords at the cube’s position, rather than its own. Hope that makes sense.
Thanks!
Not possible.
A shader only knows the information about itself, not about another object. As such there’s absolutely no way to do what you want.
There are ways around it though. The simplest way is do your look up in world space rather than object space, that way the position will be the same for both objects. You can even have a world space position offset and scaled by the position of the plane by manually passing that information to your cube shader. You wouldn’t be passing the actual vertex locations mind you, just an object relative position which you could use to again get the same look up offset for both.
If you’ve got a particularly fancy mesh and uvs and really need to copy them then you’ll need to render the object from a second camera to a render texture and pass that texture to the cube along with the appropriate offsets. That’s kind of the nuclear option.
Thanks for the quick response. I know there’s no way to do it directly from the shader… I was thinking more along the lines of getting the plane’s UVs and matching the cube’s position to it cpu side and then passing that into the shader and using it in place of texcoord for the lookup. I don’t know how I’d go about that though, so I like your second thought - that does indeed seem like the simplest option. If I offset and scale the world position correctly, it should be possible to have the same exact mapping as when doing a normal tex2D in local space, right?
If both shaders are doing the same world space math, then yes, they’ll be the same for both.