Search Unity

_World2Object confusion

Discussion in 'Shaders' started by Riz, Nov 6, 2009.

  1. Riz

    Riz

    Joined:
    Oct 5, 2009
    Posts:
    7
    Hello everybody,

    I am trying to do a special type of lighting where all scene objects are lighted up only at certain distance from light source. I am not using a real light, but a GameObject which position is passed to shader. The problem, is that I can't transform "light" position from World space to Object space. In my case GameObject is at (0,0,0) and I can see that scene acts like light source is at (0,0,0) of every object.

    Code (csharp):
    1.  
    2.  
    3. Shader "blind" {
    4.    Properties {
    5.       _Le ("_Le", Vector) = (10.0,12.0,0,0)
    6.     }
    7.     SubShader {
    8.     Pass {
    9.  
    10. CGPROGRAM
    11. #pragma vertex vert
    12. #pragma fragment frag
    13. #include "UnityCG.cginc"
    14.  
    15. struct v2f {
    16.     V2F_POS_FOG;
    17.     float3 p;
    18.     float distance;
    19. };
    20.  
    21. float4 _Le;
    22.  
    23. v2f vert (appdata_base v)
    24. {
    25.     v2f o;
    26.     o.pos = mul( glstate.matrix.mvp, v.vertex );
    27.     o.p  = v.vertex.xyz;
    28.     return o;
    29. }
    30.  
    31. half4 frag (v2f i) : COLOR
    32. {
    33.  
    34.     float4 soundPosWorld = float4(0.0,0.0,0.0,0.0); // This is coordinates of "light" source
    35.     float4 soundPos = mul( _World2Object, float4(soundPosWorld, 1.0) );
    36.  
    37.     float distance = sqrt((i.p.x - soundPos.x) * (i.p.x - soundPos.x) + (i.p.y - soundPosWorld.y) * (i.p.y - soundPos.y) + (i.p.z - soundPos.z) * (i.p.z - soundPos.z));
    38.  
    39.     float3 color = float3(1.0, 1.0, 1.0);
    40.  
    41.     if (distance > _Le.x) {
    42.         if (distance < _Le.y) {
    43.             color.r = 0.5;
    44.             color.g = 0.745;
    45.             color.b = 0.88;
    46.         }
    47.     }
    48.    
    49.     if (distance < _Le.x) {
    50.         if (distance > (_Le.x - 0.1)) {
    51.             color.r = 0.0;
    52.             color.g = 0.5;
    53.             color.b = 0.0;
    54.         }
    55.     }
    56.    
    57.     if (distance > _Le.y) {
    58.         if (distance < (_Le.y+0.1)) {
    59.             color.r = 0.5;
    60.             color.g = 0.0;
    61.             color.b = 0.0;
    62.         }
    63.     }
    64.  
    65.     return half4( color, 1 );
    66. }
    67. ENDCG
    68.  
    69.  Lighting Off
    70.  
    71.     }
    72. }
    73.  
    74. }
    75.  
    Btw, can distance be calculated in a more elegant way?
     
  2. Riz

    Riz

    Joined:
    Oct 5, 2009
    Posts:
    7
    With a great help of ToreTank this issue is solved.