Circular Movement

Although math was not necessarily my favorite subject at school and I was never the one who got all answers right, there were some branches of math that interested me, and one of them was trigonometry.

The sine, cosine, tangent functions... remember these?

The reason for anyone to know them is that these trigonometric functions are fabulously useful in coding in Flash Adobe. Example? You probably can guess one by the title :-) Yes, circular movement.

 

But before we do that, let me refresh your knowledge explaining some basis (you can skip this if you're a math geek). First, the trigonometric functions:

Sin A = a/c

Cos A = b/c

Tan A = a/b

 

Now, because Actionscript understands only radians - not degrees - you should know degrees to radian conversion:

Actionscript for that would be:

radian = degrees * pi /180;

Programming

OK. Have a look at this code. Below you can find an explanation to this.

onClipEvent(load){
radians = 0;
degrees= 0;
pos_x = random(300); // random primary x position
pos_y = random(300); // random primary y position
radius = 100;
}
onClipEvent(enterFrame){
degrees = degrees + 5; // each time degrees is increased by 5 degrees
radians = degrees * Math.PI/ 180;
trace(radians);
new_y = Math.sin(radians) * radius // because sin A = y/r
new_x = Math.cos(radians) * radius // because cos A = x/r
this._x = new_x + pos_x;
this._y = new_y + pos_y;
}

Explanation

onClipEvent(load){

onClipEvent(load) tells Actionscript what should be done when the object (on which the code is situated) is loaded.

radians = 0;
degrees= 0;
pos_x = random(300); // random primary x position
pos_y = random(300); // random primary y position
radius = 100;
}

Setting primary variables for our code.

onClipEvent(enterFrame){

onClipEvent(load) tells Actionscript to do a specified action every frame. That means that this action is executed 12 times a second when working in 12fps.

degrees = degrees + 5; // each time degrees is increased by 5 degrees
radians = degrees * Math.PI/ 180;

Every 1/12th second the degrees variable is increased by 5 degrees. That means it takes 6 seconds for the object to make a whole circle. In line 2, we use the conversion I mentioned earlier.

new_y = Math.sin(radians) * radius // because sin A = y/r
new_x = Math.cos(radians) * radius // because cos A = x/r

We're using the trigonometric functions to calculate new y and x values.

this._x = new_x + pos_x;
this._y = new_y + pos_y;
}

Finally, the current x and y values are replaced with the new ones.

That's it! We're done with coding. Pretty easy, wasn't it? If you feel like something more though, you can add additional random() function to randomize radius and other values:

 



I hope this tutorial helped you a bit. You can now move on to my other tutorials.


Average: 4.5 (35 votes)