Zecrow
Zecrow

Reputation: 233

Advanced coordinate rotation

package  {
    import flash.display.Sprite;
    import flash.geom.Point;
    import flash.events.Event;

    public class Game2 extends Sprite {

        var balls:Array;
        var radius:Number = 50;
        var centerX:Number = stage.stageWidth / 2;
        var centerY:Number = stage.stageHeight / 2;
        var i:int = 0;
        var angle:Number = 0.1;
        var sin:Number = Math.sin(angle);
        var cos:Number = Math.cos(angle);
        public function Game2() {
            init();
        }



        function init():void
        {
            balls = new Array();
            for(i = 0; i < 8; i++)
            {
                var ball:Ball = new Ball(10, 0x00FF00);
                var xposition = centerX + Math.cos(i / 8 * Math.PI * 2) * radius;
                var yposition = centerY + Math.sin(i / 8 * Math.PI * 2) * radius;
                ball.x = xposition;
                ball.y = yposition;
                addChild(ball);
                balls.push(ball);
            }

            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        function onEnterFrame(e:Event):void
        {
            for(i = 0; i < balls.length; i++)
            {
                var ball:Ball = balls[i];
                var x1:Number = ball.x - stage.stageWidth / 2;
                var y1:Number = ball.y - stage.stageHeight / 2;
                var x2:Number = cos * x1 - sin * y1;
                var y2:Number = cos * y1 + sin * x1;
                ball.x = stage.stageWidth / 2 + x2;
                ball.y = stage.stageHeight / 2 + y2;
            }


        }

    }

}

Can someone explain the work of this formula?:

var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;

i just can't figure it out, if we edit it like this:

var x2:Number = x1 - y1;
var y2:Number = x1 + y1;

all the balls are moving so fast and get out of screen bounds, and also why if we change it like this:

var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;

or

var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;

it will work equal, as far as i understanded is that here happens some kind of simetry, if we are on the left or right sides the velocity x == 0 and y is at the maximum velocity of its position the y slows down each time he get closer to the top or bottom, if we are on the top or bottom the velocity y == 0 and x is at maximum speed of his position then also slows down each time he gets closer to the right or left sides, i traced it, but i can't understand why we have to multiply it by cos and sin, i've traced this moments but still can't figure it out, can anyone explain this moment?

Upvotes: 0

Views: 264

Answers (1)

Matthias
Matthias

Reputation: 7521

The two formulas represent a rotation matrix multiplied with a vector.

Upvotes: 2

Related Questions