Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

323
Views
JavaScript: ¿Cómo hacer que una variable se acerque gradualmente a un valor objetivo a una velocidad determinada?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!