Home Contact RSS

Multiple Targets

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

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.

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Here’s the actioscript for the little ball:

  1. onClipEvent (load) {
  2.   //random placement
  3.   _x = Math.random()* 450;
  4.   _y = Math.random()* 450;
  5.   //speed is speed, higher number is slower movement
  6.   speed = (Math.random()*5)+7;
  7.   //x and y distance from target
  8.   xdist = 0;
  9.   ydist = 0;
  10. }
  11.  
  12. onClipEvent (enterFrame) {
  13.   //determine which target is closer a^2+b^2=c^2
  14.   //use a for loop to cycle through all targets,
  15.   //and assign the closest to be THE target
  16.   for (j=0; j <= _root.i; j++) {
  17.     //for the first automatically assign it as the closest
  18.     if (j == 0) {
  19.       xdist = _root.target0._x - _x;
  20.       ydist = _root.target0._y - _y;
  21.     }
  22.     //find the distance to next target
  23.     else {
  24.       //temporary distance variables
  25.       xdistT = _root["target"+j]._x - _x;
  26.       ydistT = _root["target"+j]._y - _y;
  27.       //if it is closer assign it to the closest, if not do nothing
  28.       if(Math.sqrt((xdist*xdist) + (ydist*ydist)) > Math.sqrt((xdistT*xdistT) + (ydistT*ydistT))) {
  29.         xdist = xdistT;
  30.         ydist = ydistT;
  31.       }
  32.     }
  33.   }
  34.  
  35.   //move toward the selected target
  36.   _x += xdist/speed;
  37.   _y += ydist/speed;
  38.  
  39.   //if target reached go to another random place
  40.   //if xdist is less than 2 and ydist is less than 2 and xdist is greater than 2 and ydist is greater than 2
  41.   if(xdist < 2 && ydist < 2 && xdist > -2 && ydist > -2) {
  42.     _x = Math.random() * 450;
  43.     _y = Math.random() * 450;
  44.   }
  45. }

Here’s the source flash file:
To Download the fla file.

Tags: , , , , ,

Related posts

flashden banner

Leave a Comment