T
T
Triborg-3332019-11-22 15:22:17
JavaScript
Triborg-333, 2019-11-22 15:22:17

How to make the ball follow the cursor smoothly?



How to make a smooth direction of the ball to the cursor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-11-22
@Raipon

Perhaps something like this:

window.onload = function() {
      const game = new Game('ctx');
      
      const dot = game.body[0];
      const delay = 50;
      const minOffset = 1e-3;
      
      let interval = null;
      document.addEventListener('mousemove', function(event) {
        clearInterval(interval);
        
        interval = setInterval(() => {
          const offsetX = (event.clientX - dot.myPos.x) / delay;
          const offsetY = (event.clientY - dot.myPos.y) / delay;
        
          dot.myPos = {
            x: dot.myPos.x + offsetX,
            y: dot.myPos.y + offsetY
          };
          
          // останавливаем точку
          if (Math.abs(offsetX) < minOffset && Math.abs(offsetX) < minOffset) {
            clearInterval(interval);
          }
        });
      });

    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question