Search Unity

Problem with making material more opaque with distance

Discussion in 'Scripting' started by DylanCPL, Sep 5, 2011.

  1. DylanCPL

    DylanCPL

    Joined:
    Jul 14, 2011
    Posts:
    98
    Hi, I'm trying to make my water material more opaque with distance, my only problem is that even though it does not generate any errors, it also does nothing, all the distance variables stay at 0.

    Code (csharp):
    1.  
    2. var player : GameObject;
    3. var playerdistance : float;
    4. var selfdistance : float;
    5. var distance : float;
    6.  
    7. function Update() {
    8. var playerdistance=player.transform.position.x+player.transform.position.y+player.transform.position.z);
    9. var selfdistance = (transform.position.x+transform.position.y+transform.position.z);
    10. var distance= (selfdistance - playerdistance);
    11.  
    12. renderer.material.SetFloat("_MainAlpha",distance);
    13. }
    14.  
    I know that thats not a good equation for opacity, it's just a placeholder.
    My only idea on what may be wrong is the equations for playerdistance and selfdistance.
    Any suggestions?
     
    Last edited: Sep 5, 2011
  2. DylanCPL

    DylanCPL

    Joined:
    Jul 14, 2011
    Posts:
    98
    I know I shouldn't post a question if the answer is simple, but that has stumped me for days. Apparently I at one point added var before every equation during function update and forgot to delete it which I figured out while editing my first post, which was the problem, sorry.
     
  3. Moonjump

    Moonjump

    Joined:
    Apr 15, 2010
    Posts:
    2,572
    I suspect that distance always has a value greater than 1, but needs a value between 0 and 1.

    Also look at Vector3.Distance to simplify finding the distance.
     
  4. MrBurns

    MrBurns

    Joined:
    Aug 16, 2011
    Posts:
    378
    But why should water become more opaque when you are farther away ^^? Don't get this... Maybe you should look at the water4 shader which is reading from a depth texture to define the opacity (so it is using "how far the water is away from something" instead of how far YOU are away from it)... This can easily be applied to your own shaders, its just a set of builtin unity functions.
     
  5. DylanCPL

    DylanCPL

    Joined:
    Jul 14, 2011
    Posts:
    98
    I'm not sure if I follow you...
    I think it will look more realistic if when I'm up close to the water, I can see through it, else, it should be reflecting the sky. My only problem is I'm trying to test the distance from the entire mesh and base the alpha on that, not the centre, which I can't figure out how to do.
    Any suggestions?