0

I was creating a JS script where a point follows the mouse pointer, by a given displacement PVector. I implemented a self made PVector class, I tested it and it works well.
My question is: Is there any workaround to update the mouse position inside the requestAnimationFrame(animate())

For now I am updating my mouse position inside the event handler, and it is not working well:
window.addEventListener('mousemove' e =>{ updateMousePosition() });

I have searched about this and I couldn't find a solution or maybe I didn't understand it.

minus.273
  • 755
  • 11
  • 24
  • I don't know what your `updateMousePosition` function does, but what you probably want to do here is have the `mousemove` handler update in-scope mouse position variables that you then use in in your `requestAnimationFrame` handler. – T.J. Crowder Feb 11 '20 at 07:38
  • 1
    Side note: `requestAnimationFrame(animate())` looks suspect. You pass a **function** to `requestAnimationFrame`. Unless your `animate` function *returns* a function you want called, you shouldn't be calling `animate` there. Instead: `requestAnimationFrame(animate)`. But again, it depends on what `animate` does/returns. If you're really using it to *create* and return a function, then your original is fine. – T.J. Crowder Feb 11 '20 at 07:39
  • update `x` and `y` variables in the `event`, and draw the pointer according to the `x` and `y` vars in the `animation frame` – Yosef Tukachinsky Feb 11 '20 at 07:41
  • Note that mouse events are now throttled by specs and Blink+Gecko to screen refresh rate, just like requestAnimationFrame. So if you have a problem with updating the values in the event handler from either Chrome or FF, then you'll probably face the same when moving it to the rAF callback. – Kaiido Feb 11 '20 at 07:50
  • @T.J.Crowder yes, the animate() function is calling my methods for drawing. updateMousePosition() just assigns the x and y values to a PVector. – Bogdan - Daniel Mihalcea Feb 11 '20 at 11:35
  • @T.J.Crowder If i stop moving my mouse my mouse position variable it doesn't get updated, and keeps drawing a movement vector in the old mouse position. – Bogdan - Daniel Mihalcea Feb 11 '20 at 11:39

0 Answers0