Rotation
You can make a sprite rotate by setting its rotation
property to a value in radians.
cat.rotation = 0.5;
But around which point does that rotation happen?
You’ve seen that a sprite’s top left corner represents its x
and y
position. That point is called the anchor point. If you set the sprite’s rotation
property to something like 0.5
, the rotation will happen around the sprite’s anchor point. This diagram shows what effect this will have on our cat sprite.
You can see that the anchor point, the cat’s left ear, is the center of the imaginary circle around which the cat is rotating. What if you want the sprite to rotate around its center? Change the sprite’s anchor
point so that it’s centered inside the sprite, like this:
cat.anchor.x = 0.5;
cat.anchor.y = 0.5;
The anchor.x
and anchor.y
values represent a percentage of the texture’s dimensions, from 0 to 1 (0% to 100%). Setting it to 0.5 centers the texture over the point. The location of the point itself won’t change, just the way the texture is positioned over it.
This next diagram shows what happens to the rotated sprite if you center its anchor point.
You can see that the sprite’s texture shifts up and to the left. This is an important side-effect to remember!
Just like with position
and scale
, you can set the anchor’s x and y values with one line of code like this:
cat.anchor.set(x, y)
Sprites also have a pivot
property which works in a similar way to anchor
. pivot
sets the position of the sprite’s x/y origin point. If you change the pivot point and then rotate the sprite, it will rotate around that origin point. For example, the following code will set the sprite’s pivot.x
point to 32, and its pivot.y
point to 32
cat.pivot.set(32, 32)
Assuming that the sprite is 64x64 pixels, the sprite will now rotate around its center point. But remember: if you change a sprite’s pivot point, you’ve also changed its x/y origin point.
So, what’s the difference between anchor
and pivot
? They’re really similar! anchor
shifts the origin point of the sprite’s image texture, using a 0 to 1 normalized value. pivot
shifts the origin of the sprite’s x and y point, using pixel values. Which should you use? It’s up to you. Just play around with both of them and see which you prefer.