Rotating ball around a point

Hello!

I’m trying to rotate a ball represented by a Sprite around the center of the screen. How ever the ball doesn’t follow a completely circular trajectory.

Here is the function which manages the rotation of the ball:

        var stageCenter: Point = new Point(Lib.current.stage.stageWidth / 2, Lib.current.stage.stageHeight / 2);

	ball.x = Math.cos(Math.PI * 0.500 / 180.000) * (ball.x - stageCenter.x) - Math.sin(Math.PI * 0.500 / 180.000) * (ball.y - stageCenter.y) + stageCenter.x;
	ball.y = Math.sin(Math.PI * 0.500 / 180.000) * (ball.x - stageCenter.x) + Math.cos(Math.PI * 0.500 / 180.000) * (ball.y - stageCenter.y) + stageCenter.y;

I really don’t know what’s wrong with this code.
Thank you!

It may have to do with where the origin of the ball is located (typically the upper-left corner of the sprite).

There are a number of solutions.

You can put the ball in a container sprite and offset it so that its centered in the container and rotate the container. Or you can add the offsets (1/2 ball width and 1/2 ball height) directly to your calculations.
If you created the ball using the Graphics API, you also have the option of drawing the shape so that its centered about the origin.

Actually it’s a SVG loaded with a specific library. The solution with the ball offsets it’s not working, now the ball is getting a really weird trajectory…

Your formula is way more complicated than it needs to be.

private var ball:Sprite;
private var distanceFromCenter:Float;
private var angle:Float;
private var angleIncrement:Float;

public function new() {
    ball = /* ... */;
    ball.addEventListener(Event.ENTER_FRAME, moveBall);
    angleIncrement = Math.PI / 50;
    
    distanceFromCenter = 200;
    angle = 0;
    
    //Optional: calculate distance/angle from the ball's initial location.
    //var xDist:Float = ball.x - Lib.current.stage.stageWidth / 2;
    //var yDist:Float = ball.y - Lib.current.stage.stageHeight / 2;
    //distanceFromCenter = Math.sqrt(xDist * xDist + yDist * yDist);
    //angle = Math.atan2(yDist, xDist);
}

private function moveBall(e:Event):Void {
    angle += angleIncrement;
    
    ball.x = Math.cos(angle) * distanceFromCenter
        + Lib.current.stage.stageWidth / 2 - ball.width / 2;
    ball.y = Math.sin(angle) * distanceFromCenter
        + Lib.current.stage.stageHeight / 2 - ball.height / 2;
}