Rotating sprite moves the sprite from it's original location
I'm doing a simple rotation on a sprite but there's a weird behavior where the sprite does not rotate around it's top left. I think I'm rotating along the top left of the test class instead of the sprite child. I would like to rotate the rectangle around it's top left corner (kinda like a clock hand). The code is pretty short so I'll let the code + pictures explain my problem:
package
{
import flash.display.Sprite;
public class test extends Sprite
{
public function test()
{
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0x000000);
mySprite.graphics.drawRect(开发者_Python百科100,100,6,120);
mySprite.graphics.endFill();
this.addChild(mySprite);
mySprite.rotation = 45;
}
}
}
Seems too simple to screw up, well here are the results. The red line is over the home key for reference. First pic I set mySprite.rotation=0
and second is the code shown above:
I've read a lot of stuff about rotating around a fixed point, I've tried doing it with movieclips instead of sprites, I even copy pasted a tutorial on rotation and nothing works. Why does this behavior happen and how can I fix it?
Edit: Thanks everyone, all your suggestions helped me out in different ways and they were all correct so +1, I'll just choose the solution I chose to use in my code.
If you want to rotate it from the center, try something like:
var mySprite:Sprite = new Sprite();
mySprite.x = mySprite.y = 100;
mySprite.graphics.beginFill(0x000000);
mySprite.graphics.drawRect(-3,-60,6,120);
mySprite.graphics.endFill();
this.addChild(mySprite);
mySprite.rotation = 45;
The sprite is rotating around it's top-left, but you don't have any graphics in top-left. The bar is rendered in (100, 100). Try this:
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0x000000);
mySprite.graphics.drawRect(0,0,6,120); // render in 0, 0
mySprite.graphics.endFill();
mySprite.x = 100; // move it
mySprite.y = 100;
this.addChild(mySprite);
mySprite.rotation = 45;
You are rotating the rectangle around mySprites registration point which is the same as its x/y coordinates (currently set to 0,0). You could draw the rectangle and then move it to the correct position by setting the sprites xy.
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0x000000);
mySprite.graphics.drawRect(-3, -60, 6, 120);
mySprite.graphics.endFill();
mySprite.x = 100;
mySprite.y = 100;
addChild(mySprite);
mySprite.rotation = 45;
That should work. To see how the problem was occurring, compile the below code and you'll be able to see the movement of the original bar.
for (var i:int = 0; i <= 45; i+=5) {
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0x000000,0.5);
mySprite.graphics.drawRect(100, 100, 6, 120);
mySprite.graphics.endFill();
addChild(mySprite);
mySprite.rotation = i;
}
精彩评论