Danish Ajaib
Danish Ajaib

Reputation: 109

How to position objects randomly on y-axis with a variable distance between each of the objects, which is always greater than a specific value?

I am placing 4 objects through a for-loop on the y-axis. Each object is placed randomly on the y-axis using the following method:

myObject.y = stage.stageHeight * Math.random();

The problem is sometimes the objects are too far from each other and other times they are over lapping each other. What I want to achieve is to always have some distance between each of the two objects. I want that distance to be always greater than a specific value. I have been trying to work this out for 2 days but couldn't figure it out.

Here is what I tried to get rid of overlapping:

function createObstacles():void
{
  var currentElements:Array = [];
  var myRect:Obstacle;

    for(var k:int = 0; k < 4; k++)
    {
        myRect = new Obstacle();
        addChild(myRect);
        myRect.x = stage.stageWidth + 30;

        myRect.y = stage.stageHeight * Math.random(); 
        obstacles.push(myRect);
        currentElements.push(myRect);
    }

  checkOverlap(myRect,currentElements);

}

function checkOverlap(rect:Obstacle, elements:Array)
{
   for(var n:uint = 0; n < elements.length; n++)
   {
       if(rect.hitTestObject(elements[n]))
       {
           rect.y = stage.stageHeight * Math.random();
       }
   }
}

The elements still overlap. About always keeping a distance between each of the two objects, I just couldn't get my head around that. I googled but nothing relevant returned. Any kind of help would be greatly appreciated.

Upvotes: 0

Views: 263

Answers (1)

Pan
Pan

Reputation: 2101

You can set the object's y based on the previous object'y value.

function createObstacles():void { var currentElements:Array = []; var myRect:Obstacle;

var minDistance:int = 5;//the min distance between two objects

var maxDistance:int = 10;//the max distance between two objects.

for(var k:int = 0; k < 4; k++)
{
    myRect = new Obstacle();
    addChild(myRect);
    myRect.x = stage.stageWidth + 30;

    if (k == 0)
    {
        // make sure four objects in one page
         myRect.y = stage.stageHeight/2 * Math.random(); 
    }
    else
    {
       var distance:int = (maxDistance - minDistance)*Math.random() + minDistance;

        myRect.y = obstacles[k - 1].y + distance;
    }
    obstacles.push(myRect);
    currentElements.push(myRect);
}

}

Upvotes: 1

Related Questions