10 - Movement (Swing)

Another classic "old school" effects is using a swing effect of a logo or sprite etc..

This can be asily acheived in CODEF using Javascript commands Math.cos calculating a co-ordinate. 

For example, in order to do this simple effect on the logo used below...

...we simply need to define a variable in our code. 

var sinY=0;

Then when we draw the object, we use the following commands to calculate its position.


We can choose to either move the object left to right, or up and down. (In this example, I will use a vertical swing effect, which is explained below.

Firstly we increase the value of the variable, in this case by 0.03 every loop. The higher this number, the faster the bounce, however bear in mind that the larger the area of the bounce, the speed will decrease in relation to the amount of movement requested.

Then we use our normal "draw" command, to our canvas of choice, and then the X position required (in this case, we will NOT move on the X plane (Horizontal), but we WILL move on the Y plane (Vertical), so the movement calculations are applied to the Y position.
In this case we have defined 240 as the middle position, which is where the "swing" will centre, i.e. the sprite will swing UP and DOWN from this position.

Then we use a calculation to change the Y position (i.e. move it up or down
) based upon the Cosine (Cos) of the movement vector 'sinY' * the total number of movement required (in this case 100 pixels more or less than the 240 defined earlier).
This means we will bounce from the 240 pixels Y position, upwards and downwards by a maximum of 100 pixels (140 or 340 pixels Y position) by a varying amount.

You can see this at work HERE.

Have a play around with the code and see what you can do with it!

No comments:

Post a Comment