Rotating an object around a custom point

Beginning with Sparrow 1.2, it's very easy to rotate an object around a custom point, thanks to the new “Pivot Point” feature. Nevertheless, it is interesting to know how it is done without pivot points — since the underlying principle (nesting coordinate systems) is one of the key concepts of the display tree architecture.

Using a container sprite

It's not obvious how to rotate an object around a custom point, but very easy once you have seen it. The trick is to create a sprite that contains the image, and rotate that. To stick with the analogy I described in the manual:

You pin a sheet of paper to the pin board (the pin board is the stage, the sheet of paper is the sprite). Then you pin the photo onto the sheet of paper, but move it a little upwards and to the left before that. (The pin of the sheet of paper is now exactly in the middle of the photo.) Now, rotate the the sheet of paper (the sprite) around its pin - et voilà! The photo rotates around its center.

It might be easier to understand with sample code:

// the image you want to rotate
SPImage *photo = [SPImage imageWithContentsOfFile:@"photo.png"];
 
// the sprite will contain the photo, but with an offset
// that moves the photo to its center
SPSprite *sprite = [SPSprite sprite];
photo.x = -photo.width / 2.0f;
photo.y = -photo.height / 2.0f;
[sprite addChild:photo];
 
// add the sprite to the stage (or whatever)
[self addChild:sprite];
 
// now, rotate it!
sprite.rotation = SP_D2R(110);

Using a pivot point

Beginning with Sparrow 1.2, you don't need the outer sprite. Display objects now have the properties “pivotX” and “pivotY”, which describe the root of the coordinate system of that object. When you rotate an object, it will move around the pivot point.

Thus, all you have to do is to center the pivot point in the object.

// create the image
SPImage *photo = [SPImage imageWithContentsOfFile:@"photo.png"];
 
// move the pivot point to its center
photo.pivotX = photo.width / 2.0f;
photo.pivotY = photo.height / 2.0f;
 
// now, rotate it!
photo.rotation = SP_D2R(135);

Note how moving the pivot point changes how the object rotates!

  tutorials/rotating_an_object_around_a_custom_point.txt · Last modified: 2013/09/04 13:14 by 203.92.80.243
 
Powered by DokuWiki