## 11 March 2009

### Object Movement Functions

Recently I needed some custom movie clips movement functions, but none of those free ones out there didn't fit and I had to write few of them on my own. First function is moveToPoint which uses 4 arguments, obj is Object to move (MovieClip), fx is end x point, fy is end y point and sp (speed) is number of frames to reach the goal. This means function is frame based, not time based.

`function moveToPoint(obj:Object, fx:Number, fy:Number, sp:Number) { var dx = (fx - obj._x) / sp; var dy = (fy - obj._y) / sp; var counter = 0; obj.onEnterFrame = function() {  if(counter < sp) {   obj._x += dx;   obj._y += dy;   counter += 1;  }else{   delete obj.onEnterFrame;  } }}`

OK, so dx and dy are distances object will need to move in sp frames. Counter is exit loop variable so we know when to delete onEnterFrame function. As you may noticed this is AS2.0 code.

Next function is what I was looking for. I'm using 3 arrays arguments where first array stores x positions of movement steps, second array stores y positions and third array stores speed, number of frames needed to move from one point to another. This has its down sides since if you want constant speed over entire road you have to calculate frame for each part, but this was not something I need, so roadMap function works for me just fine.

`function roadMap2(obj:Object, arx:Array, ary:Array, ars:Array) { var dx = (arx[0] - obj._x) / ars[0]; var dy = (ary[0] - obj._y) / ars[0]; var counter = 0; obj.onEnterFrame = function() {  if(counter < ars[0]) {   obj._x += dx;   obj._y += dy;   counter += 1;  }else{   delete obj.onEnterFrame;   counter = 0;   if(ars.length > 0) {    // remove first point from all arrays    arrx.splice(0, 1); arry.splice(0, 1); arrs.splice(0, 1);    roadMap2(obj_mc, arrx, arry, arrs);   }else{    delete arrx; delete arry; delete arrs;    obj.unloadMovie(); // this method is optional   }  } }}`

I'm using exactly the same thing as in moveToPoint function but difference is recursive call after point is reached and deleted from arrays. Requirement here is same length for all 3 arrays. Note also that ars array value of 1 will move desired MovieClip in single frame.

Functions usage example: (obj_mc MovieClip instance is needed on Stage)

`var arrx:Array = new Array(0, 200, 300, 400, 550);var arry:Array = new Array(200, 200, 300, 50, 200);var arrs:Array = new Array(1, 10, 10, 20, 20);roadMap2(obj_mc, arrx, arry, arrs);`

I thing there is 1000 points limit on recursive calls, so keep that in mind.

Live example coming soon.

.