Following a specific path

How can i make an object following my cursor ( but not directly) through a specific path ( something like a city plan) and every time my cursor change location the object would change path so it will stop where my cursor is?

try using hitTest or something like that.

Are there multiple routes? Does it have to choose the fastest, like a mouse chasing cheese in a maze? If yes, search for “path finding algorithm”. If no - like if there is just one crazy path and the thing has to go either left or right (or forward/backward) along it, then you could just continually test the position of the mouse in relation to the object, and change the direction of the objects movement MC when the mouse is in a different spot.

If I understand this correctly, then you want your object to be in the position on the path, that’s the shortest way from the cursor?

I don’t know how your path is made. Is it from straight lines, circles or curves?

Finding the point on a circle that’s nearest to another point is pretty easy. On a line it’s also doable. I wouldn’t want to code it for a curve… :slight_smile:

If your path is made from several segements, then you have to test each segment and pick the one with the shortest distance.

There’s some code in ‘Graphics Gems’ by Andrew Glassner that can help you with circles and lines.

It will be only lines but as jingman says it may have to find the shortest distance! The example he used ( with the mouse) is what i’m thinking of!

By the way, i can’t understand how an object can find the shorter distance on a circle

thank all of you for your help!

Not that you need it, but just to show you how a movieclip can be set to find the point on a circle where it’s nearest to the mouse:

[AS]
onEnterFrame = function() {
circle_radius = 100;

circlecenter_x = 150;
circlecenter_y = 150;

// Vector from circle center to mouse
x = _root._xmouse - circlecenter_x;
y = _root._ymouse - circlecenter_y;

// Normalize the vector
l = Math.sqrt(x * x + y * y);
x = x / l;
y = y / l;

// Calculate point on circle
mc_x = circlecenter_x + circle_radius * x;
mc_y = circlecenter_y + circle_radius * y;

// Move the movieclip
<movieclip>._x = mc_x;  // <- change to your clip name
<movieclip>._y = mc_y;  // <- change to your clip name

}
[/AS]

Thank you very much Hans Kilian for sending me the code.

No problem. Glad I could help.