0

I was asked to draw a line between two given points using surface shader. The point is given in texture coordinate (between 0 and 1) and directly goes into the surface shader in Unity. I want to do this by calculating the pixel position and see if it is on that line. So I either try to translate the texture corrdinate to world pos, or i get the position of pixel in relative to that texture coordinate.

But I only found worldPos and screenPos in unity shader manual. Is there some way i can get the position in texture coordinate (or at least get the size of the textured object in world pos?)

Ice.Rain
  • 113
  • 2
  • 4
  • 12

1 Answers1

1

Here is a simple example:

Shader "Line" {
    Properties {
        // Easiest way to get access of UVs in surface shaders is to define a texture
        _MainTex("Texture", 2D) = "white"{}
        // We can pack both points into one vector
        _Line("Start Pos (xy), End Pos (zw)", Vector) = (0, 0, 1, 1) 

    }

    SubShader {

        Tags { "RenderType" = "Opaque" }
        CGPROGRAM
        #pragma surface surf Lambert
        sampler2D _MainTex;
        float4 _Line;

        struct Input {
            // This UV value will now represent the pixel coordinate in UV space
            float2 uv_MainTex;
        };
        void surf (Input IN, inout SurfaceOutput o) {
            float2 start = _Line.xy;
            float2 end = _Line.zw;
            float2 pos = IN.uv_MainTex.xy;

            // Do some calculations

            return fixed4(1, 1, 1, 1);
        }
        ENDCG
    }
}

Here is a good post on how to calculate whether a point is on a line:

How to check if a point lies on a line between 2 other points

Let's say you define a function from this with the following signature:

inline bool IsPointOnLine(float2 p, float2 l1, float2 l2)

Then for return value, you can put this:

return IsPointOnLine(pos, start, end) ? _LineColor : _BackgroundColor

If you want UV coordinates without using a texture, i recommend making a vertex fragment shader instead and defining float2 uv : TEXCOORD0 inside the appdata/VertexInput struct. You can then pass that on to the fragment shader inside the vertex function.

Kalle Halvarsson
  • 1,240
  • 1
  • 7
  • 15