Question

I'm trying to work out a way for my game to recognise when two instances of this array have the same x or y position as another and if so to move re randomize the position of one of the instances.:

for(i=0;i<8;i++) {
        PlatformInstance[i] =new Platform();
     PlatformInstance[i].y= Math.random()*900;
     PlatformInstance[i].x= Math.random() *1500;
     stage.addChild(PlatformInstance[i]);

 }

the problem i have is that the code i try detects that one platform instance has the same position as the SAME platform instance, and will constantly re randomize the position. is there a way to differentiate between different instances?

thanks very much in advance.

EDIT

The only code i could think of was running an if statement in a loop to see whether

If (PlatformInstance[i].y == PlatformInstance[i].y)

Obviously this wouldnt work and thinking of it i know it wouldn't however i was wondering if there was a way to do:

 If (Platforminstance[i].y == "other" Platforminstance[i].y

or some other words to that effect

Était-ce utile?

La solution

You don't seem to have a clear understanding of how arrays work, I recommend looking into that. Something like this should work

   i=0;
   j=0;
   while( i < PlatformInstance.length -1) {
      j++;
      if (j == PlatformInstance.length) {
         i++;
         j=i+1;
      }

      if( (Math.abs(PlatformInstance[i].x - PlatformInstance[j].x) < platformWidth)
      || (Math.abs(PlatformInstance[i].y - PlatformInstance[j].y) < platformHeight) ) {

         PlatformInstance[j].y= Math.random()*900;
         PlatformInstance[j].x= Math.random() *1500;
         //Now you'll have start checking at the beginning again since you moved one
         i=0;
         j=0;
         continue;
      }
   }

Also as it was previously mentioned, PlatformInstance is not a good name for an array. Only Class names should start with a capital letter. And an array of platforms should not be called an "instance". I would recommend changing it to simply platforms

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top