There is a simple formula to move an object to coordinates with smoothing.
The speed will decrease with smooth during the time.
speed = distance_between_objects / smoothing
The distance will decrease because the distance will decrease too.
If I set values I got:
object.x = 50
targetX = 100
speedX = (targetX – object.x) / 5
On the first frame: speed = 10
object.x += (100 – 50) /5 > 50/5 > 10
> object.x = 50+10 = 60On the second frame: speed = 8
object.x += (100 – 60) /5 > 40/5 = 8
> object.x = 60 + 8 = 68On the third frame: speed = 6,4
object.x += (100 – 68) / 5 > 32/5 = 6,4
> object.x = 68 + 6,4 = 74,4etc.
On the 100th frame: speed = 0
object.x += (100 – 100) / 5 > 0 /5 = 0
> object.x = 100 + 0 = 100
Source:
// Add a mouse event on the stage stage.addEventListener(MouseEvent.CLICK, click); function click(pEvent) { // On click set the new x and y coordinates myBall.targetX = stage.mouseX; myBall.targetY = stage.mouseY; } // Set default coordinates myBall.targetX = 200; myBall.targetY = 200; // Add an enter frame event on the ball myBall.addEventListener(Event.ENTER_FRAME, ballEnterFrame); function ballEnterFrame(pEvent) { // On enter frame move the ball to the target coordinates var b = pEvent.currentTarget; b.x += (b.targetX - b.x) / 8; b.y += (b.targetY - b.y) / 8; }
Exemple:
[swf:/wp-content/uploads/2011/01/www.benoitfreslon.com-Move-an-object-to-coordinates-with-smoothing.swf 550 400]
Download source: www.benoitfreslon.com Move an object to coordinates with smoothing.zip