[FMX04] Movie Clips: Crowd Control

30 movie clips. *p0 *through p29. They chase the leader movie clip in a swarm; however, to make sure they don’t all occupy the same space, I implemented this code in the onEnterFrame block:

//*pik* is the number of movie clips onstage
for (var i = 0; i<pik-1; i++) {
  var dotA:MovieClip = this["p"+i];
  for (var j = i+1; j<pik; j++) {
  var dotB:MovieClip = this["p"+j];
  var dx:Number = dotB._x-dotA._x;
  var dy:Number = dotB._y-dotA._y;
  var dist:Number = Math.sqrt(dx*dx+dy*dy);
  if (dist<5) {
	var rx:Number = dx/dist/2;
	var ry:Number = dy/dist/2;
	dotA._x -= rx;
	dotA._y -= ry;
	dotB._x += rx;
	dotB._y += ry;
  }
  }
}

All well and good: that code successfully separates the Movie Clips when they run into one another. I added terrain, too, implementing this:

for (var i = 0; i<pik; i++) {
  var dotA:MovieClip = this["p"+i];
  for (a=0; a<360; a += 45) {
	var x:Number = Math.sin(a*(Math.PI/180));
	var y:Number = Math.cos(a*(Math.PI/180));
	while (land.hitTest(dotA._x+x*3, dotA._y-y*3, true)) {
	  dotA._x -= x/2;
	  dotA._y += y/2;
	}
  }
}

Problem is, the little buggers are still zooming through land. It’s a conflict between the two blocks. They get moved apart, one gets too far “into” the terrain, and is propelled outwards in the wrong direction.

[center]
Try it yourself: walk into the little fish hook shape, trap some *pikmin *in there, and then walk above it. Notice that those inside disappear, and then reappear outside.
[/center]