javascriptreactjsanimationreact-three-fiberlerp

How to Use Negative Values in Lerp Function as Alpha Parameter


I am trying to animate some text on the screen in two ways:

  1. Move its Y position from 1 to -1 [already finished]
  2. Shift its RGB color value from white(255,255,255) to green(149,184,6) [need help with]

I am using the Linear Interpolation function from npm lerp to calculate a value between each RGB color channel.

const r = Math.floor(lerp(255, 149, alpha));
const g = Math.floor(lerp(255, 184, alpha));
const b = Math.floor(lerp(255, 6, alpha));

The lerp function alpha parameter requires a percentage decimal value from 0 to 1, but I would like to use the texts position from -1 to 1 as the dynamic alpha value while the texts position changes.

To visualize this animation, please watch this video

Using react-three-fiber, I am changing the text's color value using this line:

ref.current.color = `rgb(${r}, ${g}, ${b})`;

I need help writing a function that takes in an input value between 1 and -1, and then converts it to an output value between 0 and 1 for the alpha parameter in the lerp function.

function translate(positionY){
  //translates
}
const positionY = -0.5;
console.log(translate(positionY)) //.75

enter image description here

This function will be used to get the alpha for the lerp function:

const r = Math.floor(lerp(255, 149, translate(positionY)));
const g = Math.floor(lerp(255, 184, translate(positionY)));
const b = Math.floor(lerp(255, 6, translate(positionY)));

Solution

  • Ok so this linear stuff basically means that between 2 points there's only one line. So if you got 2 points right, then you got the right formula for all other points on the line.

    So I started with [-1, 1] to [0, 1] transformation. It's clear to see that there should be /2 there because the range is double. But before we do I 'translate' it so that -1 will be equal 0 (and when I /2 it will stay 0).

    Then I needed to reverse the 0 with 1 for the output, so I did a minus 1 for the result. Frankly I tried apply same logic but was too lazy.

    Then I remembered I had an answer about that. It's a function that gets (x1,y1, x2, y2) and returns a linear function.

    var x1 = -1;
    var x2 = 1;
    
    var y1 = 1;
    var y2 = 0;
    
    var calcY = getLinearFunction(x1, y1, x2, y2);
    console.log(calcY(-1))
    console.log(calcY(1))
    
    function getLinearFunction(x1, y1, x2, y2) {
      var slope = (y2 - y1) / (x2 - x1);
      return function(x) {
        return slope * (x - x1) + y1;
      }
    }