An actionscript exercise. Trying to get a movie clip to go to the closest dynamically created target. Click the button to make more targets. Draggable targets. Move the targets around to see the ball’s target change. Source file below.
Here’s the actioscript for the little ball:
- onClipEvent (load) {
- //random placement
- _x = Math.random()* 450;
- _y = Math.random()* 450;
- //speed is speed, higher number is slower movement
- speed = (Math.random()*5)+7;
- //x and y distance from target
- xdist = 0;
- ydist = 0;
- }
- onClipEvent (enterFrame) {
- //determine which target is closer a^2+b^2=c^2
- //use a for loop to cycle through all targets,
- //and assign the closest to be THE target
- for (j=0; j <= _root.i; j++) {
- //for the first automatically assign it as the closest
- if (j == 0) {
- xdist = _root.target0._x - _x;
- ydist = _root.target0._y - _y;
- }
- //find the distance to next target
- else {
- //temporary distance variables
- xdistT = _root["target"+j]._x - _x;
- ydistT = _root["target"+j]._y - _y;
- //if it is closer assign it to the closest, if not do nothing
- if(Math.sqrt((xdist*xdist) + (ydist*ydist)) > Math.sqrt((xdistT*xdistT) + (ydistT*ydistT))) {
- xdist = xdistT;
- ydist = ydistT;
- }
- }
- }
- //move toward the selected target
- _x += xdist/speed;
- _y += ydist/speed;
- //if target reached go to another random place
- //if xdist is less than 2 and ydist is less than 2 and xdist is greater than 2 and ydist is greater than 2
- if(xdist < 2 && ydist < 2 && xdist > -2 && ydist > -2) {
- _x = Math.random() * 450;
- _y = Math.random() * 450;
- }
- }
Here’s the source flash file:
To Download the fla file.



