Flash - random motion and rotation - Actionscript 2
Back again, my pet tadpoles (they still haven't grown into frogs yet!). This time I am going to explain the actionscript that makes them move, turn and run from the mouse. Firstly, heres an example of what they do (move your mouse over them and watch 'em swim away):
The first thing is to create 2 movie clips, one which is the tadpole itself the other is the movie that the mouse drags with it, in my example it is a transparent square 20 pixels height / width. Drag them to the stage. Give the mouse movie an instance name, for example 'mouse_mc', and on the first frame of your flash project include the following actionscript:
var mouseListener:Object = new Object();
mouseListener.onMouseMove = function() {
mouse_mc._x = _xmouse;
mouse_mc._y = _ymouse;
}
Mouse.addListener(mouseListener);
This script basically attaches the movie to the mouse, so the mouse drags it around. This is used later for the hitTest which causes the tadpole to swim away when the mouse_mc touches it. OK, now for the tadpole. Open the tadpole movie and on it's first frame enter this actionscript:
acceleration = 20; // speed of the tadpole
newpos = function ()
{
ranx = random(600); // width of the area you want your tadpole to stay within
rany = random(400); // height of the area
};
newpos();
this.onEnterFrame = function()
{
// figure direction of movement, relative to current position
var dx = ranx-this._x;
var dy = rany-this._y;
// figure angle in radians
var ar = Math.atan2(dy,dx);
// convert to rotation in degrees
this._rotation = ar*180/Math.PI;
this._x += dx/acceleration;
this._y += dy/acceleration;
if (Math.abs(dx) < 1 || Math.abs(dy) < 1) {
newpos(); // move the tadpole
}
// if the mouse movie colides with it move in a different direction
if(this.hitTest(_root.mouse_mc)){ this.newpos();}
}
Once you have done this you can duplicate the tadpole movie clip as many times as you want, to create a whole swarm of tadpoles! Be sure to give each duplicate a unique instance name eg. t1, t2, t3 etc.






This is very cool, thank you for sharing. I can't wait to try it
Hi, I tried this out and am having trouble getting it to work. Am I supposed to have 2 different layers, one for tadpole and one for mouse_mc? Also, my transparent pixels don't seem to be attached to my mouse…
Hi Sherry
They can be on separate layers, or both the same layer, it shouldn’t matter. Did you give the movie clips instance names in the ‘properties’ panel?
Sam
Hi there, just wondering if you’d have an tips on converting this to AS3. I’m very new to Flash and have been trying to do it all day!
Thanks in advance,
bex.