Random Movement Tutorial

http://www.kirupa.com/developer/mx/random_motionMX.htm

This tutorial works for me when the random object moves on the main timeline, but when I apply the code to a movie clip inside another movie clip, it won’t work. I only see jumpy movement with no smooth tween between each jump.

It doesn’t work because the functions are not defined in _root anymore when you load the SWF into a MovieClip. Remove _root from the code. :wink:
[AS]function getdistance(x, y, x1, y1) {
var run, rise;
run = x1-x;
rise = y1-y;
return (hyp(run, rise));
}
function hyp(a, b) {
return (Math.sqrt(aa+bb));
}
MovieClip.prototype.reset = function() {
width = 300;
height = 200;
var dist, norm;
this.x = this._x;
this.y = this._y;
this.speed = Math.random()*4+2;
this.targx = Math.random()*width;
this.targy = Math.random()*height;
dist = getdistance(this.x, this.y, this.targx, this.targy);
norm = this.speed/dist;
this.diffx = (this.targx-this.x)*norm;
this.diffy = (this.targy-this.y)*norm;
};
MovieClip.prototype.move = function() {
if (getdistance(this.x, this.y, this.targx, this.targy)>this.speed) {
this.x += this.diffx;
this.y += this.diffy;
} else {
this.x = this.targx;
this.y = this.targy;
if (!this.t) {
this.t = getTimer();
}
if (getTimer()-this.t>1000) {
this.reset();
this.t = 0;
}
}
this._x = this.x;
this._y = this.y;
};[/AS]

:slight_smile: It worked! Thanks again!

You’re welcome. =)