Tenemos x que representa un valor activo, y representa el valor que queremos que alcance el primero (puede ser decimal y/o negativo), z describe qué tan rápido el primero persigue al segundo. El código se ejecuta en un intervalo y cada iteración está destinada a acercar el valor de x a y por una cantidad z , en función de qué tan adelante o atrás esté el valor de su objetivo. El valor objetivo puede cambiar a cualquier otra cosa entre iteraciones.
Para un ejemplo simple: si el valor actual es 0, el valor objetivo al que estamos interpolando es 1, mientras que el tiempo probablemente tenga un valor predeterminado de 1. El resultado debería verse así:
Iteration 0: x = 0 Iteration 1: x = 0.5 Iteration 2: x = 0.75 Iteration 3: x = 0.875 Iteration 4: x = 0.9375 x nunca llegar a 1 está bien, ya que habrá algún umbral en el que detenerse, por ejemplo: if(Math.abs(y - x) < 0.125) x = y . Principalmente tengo un problema con las matemáticas para hacer que x persiga a y de forma curva (más lento cuanto más se acerca). Intenté simplemente usar x = (x + y) / 2 , lo que acercaría suavemente el valor según lo deseado, pero no estoy seguro de cómo maneja los números negativos o dónde enchufar z para que también pueda controlar la velocidad.
Puede usar esta fórmula para cada iteración:
x += (target - x) * speed; let x = 0; let speed = 0.5; let target = 1; const THRESHOLD = 0.001; while(Math.abs(x - target) > THRESHOLD) { x += (target - x) * speed; console.log(x); }Aquí hay un ejemplo usando esta técnica:
let targetX = 0, targetY = 0; let x = 0, y = 0; const box = document.querySelector('.box'); let speed = 0.1; document.body.addEventListener('mousemove', ({x, y}) => { [targetX, targetY] = [x, y]; }); const tick = () => { x += (targetX - x) * speed; y += (targetY - y) * speed; box.style.left = `${x}px`; box.style.top = `${y}px`; requestAnimationFrame(tick); } requestAnimationFrame(tick); body { height: 100vh; } .box { width: 4px; height: 4px; background-color: red; position: absolute; } <div class="box"></div>