marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
2.99k stars 790 forks source link

Chapter 15: Solution for Mouse trail exercise (hint) #541

Closed alexpi closed 3 years ago

alexpi commented 3 years ago

Hi,

I am trying to solve this exercise creating the alternative effect suggested in the hint. My version works, but the motion produced is not exactly the one required. Any suggestions or a solution?

class Dot {
  constructor(speed) {
    this.x = 0;
    this.y = 0;
    this.speed = speed;
  }

  create() {
    const dotEl = document.createElement('div');
    dotEl.className = 'trail';
    this.el = dotEl;
    return dotEl;
  }
}

const dots = [];

for (let i = 0; i < 12; i++) {
  const dot = new Dot(i + 1);
  document.body.appendChild(dot.create());
  dots.push(dot);
}

let mouse = { x: 0, y: 0 };

window.addEventListener('mousemove', event => {
  mouse.x = event.pageX - 3;
  mouse.y = event.pageY - 3;
});

const draw = (time, lastTime) => {
  dots.forEach(dot => {
    /*if (lastTime != null) { Account for frame rate differences }*/

    dot.x += (mouse.x - dot.x) / dot.speed;
    dot.y += (mouse.y - dot.y) / dot.speed;

    dot.el.style.left = dot.x + 'px';
    dot.el.style.top = dot.y + 'px';
  });

  requestAnimationFrame(newTime => draw(newTime, time));
}

requestAnimationFrame(draw);
marijnh commented 3 years ago

https://eloquentjavascript.net/code/#15.2 has a "look at the solution" button that'll show my solution.

alexpi commented 3 years ago

Yes, I am aware of that. I was asking about the alternative way to solve it, as you write inside the hint: "Another interesting effect can be achieved by modeling a simple physics system."

marijnh commented 3 years ago

I won't have time to debug your solution, and you didn't specify how the effect differs from what you were going for, but at a glance, your definition of speed seems very different from how it tends to be defined in physics (where motion is speed × time, and speed is changed by acceleration based on forces—for example by a simulated spring between the particles and the mouse position.)

alexpi commented 3 years ago

Ok, thanks for the hints.