Hey kids,
I’ve been working on a banner that involves repulsion physics,
after a bit of research, trial and error this is what I came up with. I know it's been done a million times but I thought I'd do it one more ‘cause it’s kind of fun and might be useful to someone in the
future. It involves high school physics (remember that thing?).
Anyway, this is the juicy part of the code to be constantly
triggered for animation:
//distance between mouse and object on
the axis’
xDif = this.parent.mouseX -
this.x;
yDif = this.parent.mouseY -
this.y;
//the length of the hypotenuse using Pythagoras
distance = Math.sqrt(xDif*xDif+yDif*yDif);
//the “magic”
number to give us the perfect repulsion
tempX = this.x-(force/distance)*(xDif/distance);
tempY = this.y-(force/distance)*(yDif/distance);
//the new coordinates,
based on half the distance between current pos and our initial pos + the magic number
this.x=(homex-this.x)/2+tempX;
this.y=(homey-this.y)/2+tempY;
So you also need to instantiate three vars on initalisation:
//these act as an anchor point for the object to return to
private var homex:Number;
private var homey:Number;
//force is the level of repulsion, add or subtract a zero from the end
Private var force:int = 2000;
REPULSION, coming to a banner near you!