Saturday, October 23, 2010

Create an elastic spring effect using AS3

Today we will learn how to create a spring effect on a MovieClip.

Here's an example to show you what I'm talking about:


I'm using one class for this MC. The most complex thing in it is the formula itself. Here's the code:

package cl.kirill
{
import flash.events.Event;
import flash.display.MovieClip;

public class Spring extends MovieClip
{
private var vx:Number = 0;
private var vy:Number = 0;
private var px:Number = 0;
private var py:Number = 0;

private var elasticity:Number = 0.8;
private var strength:Number = 0.1;

public function Spring()
{
this.addEventListener(Event.ENTER_FRAME, SpringManager);
}

private function SpringManager(Event):void
{
vx = stage.mouseX - this.x;
vy = stage.mouseY - this.y;
px = px * elasticity + vx * strength;
py = py * elasticity + vy * strength;
this.x += px;
this.y += py;
}

}

}

I'm only going to try to explain the formula here.

Vx and px variables are the distance between the mouse and the object on both axises.

The px and py - the next distances for the object to go. How is it calculated? Basically, it is the "previous px/py plus the distance", so we can just leave it px + vx (py + vy) but the results won't be that great. That's why we're adding elasticity and strength variables - to make the values smaller and be able to modify the force of the spring.

Play around with elasticity and strength to get the results you need.

Hope this was helpful. Thanks for reading!

4 comments:

Anonymous said...

Good ;)

Anonymous said...

Nice one!!! =)

Anonymous said...

Proper!!!!!!!!!!!

Dan said...

THANK YOU@!!!!

Post a Comment