05 June 2009

Using ActionScript Point class distance method for constant speed moving in roadMap function

This have to be longest post title ever, at least it is in my blogging history, but it precisely explains post subject and I was so tempted to use it, I couldn't resist.

Ok, first of all if you are not familiar with roadMap function, don't worry, it's a custom function which enables movie clip movement along given points on Stage. Read about it in this post and download example.

Code works just fine, but there is one thing missing. Object speed between different points is inside arrs Array and has to be added manually, thus it is very hard to achieve same speed along entire path without a lot of calculations. To address this issue some basic math knowledge is required.

If we accept that speed = distance / time, to achieve constant speed we have to know distances between different points. Lets say path consist of two parts, first one is 10 pixels and second is 100 pixels. We want our object to move with speed 10 pixels per frame on entire path. In that case v1, speed on part one should be 10 pixels / frame same as v2, speed on second part. All we have to do is to push value of (distance / 10) to arrs Array and constant speed is there, because actually we are pushing values for object speed.

Changes we have to make are inside onMouseUp function where instead

arrs.push(someValue);

we have next code:


if(arrx.length > 1) {
var point_1:Point = new Point(arrx[arrx.length-1], arry[arry.length-1]);
var point_2:Point = new Point(arrx[arrx.length-2], arry[arry.length-2]);
var distanceBetween:Number = Point.distance(point_1, point_2);
arrs.push(distanceBetween/10);
}else{
var point_1:Point = new Point(arrx[arrx.length-1], arry[arry.length-1]);
var point_2:Point = new Point(obj_mc._x, obj_mc._y);
var distanceBetween:Number = Point.distance(point_1, point_2);
arrs.push(distanceBetween/10);
}


Don't forget to add import flash.geom.Point; at the beginning of code. There is nothing to explain here, we just use Point class distance method to calculate speeds and push those values into arrs Array. That's how we achieve constant speed moving in roadMap function, just as title says.

Live example:


download code : :







*_*

1 comments:

samBrown said...

pretty cool thanks for the code - going to play around with this later. I can see many practical applications for it (via Twitter)

 

template by blogger templates