Friday, February 23, 2007

Using Math.cos() to make an object swing

Math.cos() is often used in many animation applications, such as when you need to determine the x and y locations of an object that revolves around another object in a circle. I know many people see the word "cos" and think "oh no, not trigonometry!" But don't worry. This technique does not require you to understand trigonometry, but it definitely helps to know it.

The result of our swinging object should look like this:


How do we achieve this using the Math.cos() method? Well, leaving out the trigonometry terms, we know that if we give its parameter a number n, where n can be any number, it will always give back a number between -1 and 1. This characteristic allows us to write a formula that computes the rotation property of an object at any given point:

    mc._rotation = Math.cos(n)*force;

The variable force basically enhances the effect of the number, because the one given by Math.cos() is so small (less than 1). So all we need to do now is increment n:

    var force = 20;
    var n = 0;
    function swing() {
        n += 0.3;
        this._rotation = Math.cos(n)*force;
    }
    mc.onEnterFrame = swing;

This technique can be useful in other animation applications you might have seen, such as falling leaves:

Download the source

or Newton's Cradle:

Download the source

You can also download the source of the first example here. And for a more thorough understanding of trigonometry and its real world applications to animation, I encourage researching into it more, because this post is only breaking the tip of the iceberg.

3 comments:

G.C. McDowell said...

Using COS is a great way to control periodic motion. I created undulating squid tentacles based on the same principle.

http://www.kirupa.com/forum/showthread.php?t=250844

Star Trek Ruminations | www.humblevoice.com/AlcabyBee

Anonymous said...

Can someone please help me stop the swing...i have tried everyting i can think of ;)

Mario said...

Thanks for posting this. It has helped me out alot.