Arg - new clip conundrum

Hi guys, I’ve been reading this site for a while now but it’s only now that I have a problem that I turn to you guys in the forums for help… stupid unsociable me.

I’m new to ActionScript development, and I’ve been able to figure out pretty much everything on my own so far, but this particular problem really has me stumped. I’m totally at my wits end here, so maybe one of you smarty folks can help me out.

The following code is a stripped down version of what I’m trying to do with a game-type application. Basically I create some new movie clips, put them in an array, give them each unique attributes, and then refer to those attributes later in another function. When I do this, the attributes for ALL clips have all been set to the attributes of the last clip created! Which in this case means that all the moving elements have the same velocity, when really I want them each to have different ones.

BaseClip is just an already existing clip that I use as a base for the newly created clips.


  var iDesiredClips = 4;
  var Clips = new Array(iDesiredClips);
  var bSpawnedClips = false;
  
  BaseClip.Velocity = new Array(0, 0);
  
  setInterval(MainGame, 15);
  
  function MainGame()
  {
  	if (!bSpawnedClips)
  	{
  		SpawnClips();
  		bSpawnedClips = true;
  	}
  	
  	for (var i = 0; i < iDesiredClips; i++)
  	{
  		UpdateClips(Clips*);
  	}
  }
  
  function SpawnClips()
  {
  	for (var i = 0; i < iDesiredClips; i++)
  	{
  		BaseClip.duplicateMovieClip("clip"+i, i, BaseClip);
  		
  		Clips* = _root["clip"+i];
  		
  		Clips*.Velocity[0] = Math.random() * 5;
  		Clips*.Velocity[1] = Math.random() * 5;
  		
 		trace("created " + Clips*._name + ": " + Clips*.Velocity[0] + ", " + Clips*.Velocity[1]);
  	}
  }
  
  function UpdateClips(Clip)
  {
  	Clip._x += Clip.Velocity[0];
  	Clip._y += Clip.Velocity[1];
  }
  

Thanks in advance, guys!

In actionscript Arrays are passed as reference types not primitives. When you use BaseClip as the initObject in the duplicate movieclip call, you are implicitly assigning the Velocity array to duplicate as a reference. As a result subsequent changes to the indices of the Velocity array are actually happening on the same array. And since the last clip is the one changing the Velocity, the velocity takes its value then onwards.

The solution is to have a separate array for each clip instead.


// in the SpawnClips method
BaseClip.duplicateMovieClip("clip"+i, i, BaseClip);

Clips* = _root["clip"+i];

// reinitializing the Velocity array for each clip
Clips*.Velocity = new Array ();
Clips*.Velocity[0] = Math.random() * 5;
Clips*.Velocity[1] = Math.random() * 5;

D’OH. That would explain a lot. That wasn’t clear to me from the reference material I read. Thank you very much for clarifying that for me sir!