Search code examples
ioscalayercaanimationanchorpoint

How to create a CAAnimation effect like moon rotates around the earth and rotates by itself at the same time in IOS?


I know it is simple to create the effect making the moon circling around the earth in IOS. Suppose the moon is a CALayer object, just change the anchorPoint of this object to the earth then it will animate circling around the earth. But how to create the moon that rotate by itself at the same time? since the moon can only have one anchorPoint, seems I can not make this CALayer object rotate by itself anymore. What do you guys think? thanks.


Solution

  • Use two layers.

    • One is an invisible "arm" reaching from the earth to the moon. It does a rotation transform around its anchor point, which is the center of the earth. This causes the moon, out at the end of the "arm", to revolve around the earth.

    • The other is the moon. It is a sublayer of the "arm", sitting out at the end of the arm. If you want it to rotate independently, rotate it round its anchor point, which is its own center.

    (Be aware, however, that the real moon does not do this. For the real moon, the "arm" is sufficient, because the real moon rotates in sync with its own revolution around the earth - so that we see always the same face of the moon.)