Search code examples
javascriptcsstwo.js

Rotate a Two.js object in its position


I have a large circle with smaller ones inside made using two.js.

greninja-aegislash-goodra

My problem is that these two do not rotate in their own place but in the top left axis. I want the group of circles (circlesGroup) rotate only inside the large one in a static position. The circlesGroup and the large circle are grouped together as rotatoGroup.

two.bind('update', function(frameCount, timeDelta) {
  circlesGroup.rotation = frameCount / 120;
});

two.bind('update', function(frameCount, timeDelta) {
  rotatoGroup.rotation = frameCount / 60;
});

The whole code is in CodePen.


Solution

  • All visible shapes when invoked with two.make... ( circles, rectangles, polygons, and lines ) are oriented in the center like this Adobe Illustrator example:

    A circle with its origin at the center of the circle

    When this shape's translation, rotation, or scale change those changes will be reflected as transformations about the center of the shape.

    Two.Groups however do not behave this way. Think of them as display-less rectangles. They're origin, i.e group.translation vector, always begins at (0, 0). In your case you can deal with this by normalizing the translation your defining on all your circles.

    Example 1: Predefined in normalized space

    In this codepen example we're defining the position of all the circles around -100, 100, effectively half the radius in both positive-and-negative x-and-y directions. Once we've defined the circles within these constraints we can move the whole group with group.translation.set to place it in the center of the screen. Now when the circles rotate they are perceived as rotating around themselves.

    Example 2: Normalizing after the fact

    In this codepen example we're working with what we already have. A Two.Group that contains all of our shapes ( the bigger circle as well as the array of the smaller circles ). By using the method group.center(); ( line 31 ) we can normalize the children of the group to be around (0, 0). We can then change the translation of the group in order to be in the desired position.

    N.B: This example is a bit complicated because it invokes underscore's defer method which forces the centering of the group after all the changes have been registered. I'm in the process of fixing this.