Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Bi-Lerp

Discussion in 'Scripting' started by Deleted User, Mar 22, 2013.

  1. Deleted User

    Deleted User

    Guest

    I have had a look through but cant seem to find a bi-linear interpolation function in Unity. Can anyone tell me if there is one or not for certain before I go and roll my own?

    Just to clarify if anyone knows it by another name, I am looking for a function for interpolating x and y simultaneously in a quad. The function signature would take in an xy or uv value, and four other values

    Much appreciated,

    Luke
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    There isn't one built-in.

    --Eric
     
  3. Brian-Stone

    Brian-Stone

    Joined:
    Jun 9, 2012
    Posts:
    222
    As Bilinear interpolation is literally just the square of linear interpolation, so you can do it with Lerp alone. You just have to interpolate across one of the axes first to get two interpolated points, and then interpolate between those two points down the other axis. That's all the magic there is to bilinear interpolation.

    Bilinear interpolation of a quadrilateral
    Code (csharp):
    1.  
    2. // Some quadrilateral with position vectors a, b, c, and d.
    3. // a---b
    4. // |     |
    5. // c---d
    6. Vector3 a = new Vector3(0, 0, 0);
    7. Vector3 b = new Vector3(5, 0, 0);
    8. Vector3 c = new Vector3(0, 5, 0);
    9. Vector3 d = new Vector3(5, 5, 0);
    10. float u = 0.1f; // relative position on the "horizontal" axis between a and b, or c and d.
    11. float v = 0.8f; // relative position on the "vertical" axis between a and c, or b and d.
    12. Vector3 ab = Vector3.Lerp(a, b, u); // interpolation of a and b by u
    13. Vector3 cd = Vector3.Lerp(c, d, u); // interpolation of c and d by u
    14. Vector3 P = Vector3.Lerp(ab, cd, v); // interpolation of the interpolation of a and b and c and d by u, by v
    15.  
    Alternative you can represent the entire operation as a single equation...
    P = (d*u + c*(1-u))*v + (b*u + a*(1-u))*(1-v);

    Code and equation are off the cuff, so if you find an error please let me know and I'll make the corrections.
     
    anastasia-vf likes this.