Search code examples
javascriptanimationpaperjs

Animate segments and position in Paper.js


I need to develop 2 animations on a polygon:

  1. automatic rotation of each segments
  2. the polygon follows the mouse movements

I'm trying to do that with this code:

// onMouseMove
tool.onMouseMove = function (event) {
  mousePoint = event.point;
};

// onFrame
view.onFrame = function (event) {

  // Animation 1: Automatic circular rotation of each segment
  for (var i = 0; i < polygon.segments.length; i++) {
    var offsetRotation = new Point(Math.cos(event.time + i * 2), Math.sin(event.time + i * 2)).multiply(10);
    polygon.segments[i].point = polygonCached.segments[i].point.add(offsetRotation);
  }

  // Animation 2: the polygon moves following the mouse movements with transition
  var delta = mousePoint.subtract(polygon.position).divide(15);
  polygon.position = polygon.position.add(delta);

};

Here is the whole code: https://codepen.io/anon/pen/YMgEEe?editors=0010

With the above code the automatic rotation of each segments works and the polygon doesn't follow the mouse at all and also without the transition. Instead, commenting the automatic rotation animation it correctly follows the mouse with transition.

To check if transition works I move the mouse cursor outside of browser window and then go back from another point. Now you'll see no transition when the polygon moves.

Where I'm wrong?


Solution

  • Just move the polygonCached as well.

    polygonCached.position = polygonCached.position.add(delta);

    https://codepen.io/arthursw/pen/LvKPXo

    The cached version of the polygon was not moving, so each time you rotated your points, their position was reset.