Question

I am trying to figure out how to spawn a random number of cells, but every time I run the program, I always end up with one cell only.

How come the number of cells spawned is always 1 when it can go up to 50? (since I made the p variable a random number between 1 and 50).

var myCell:Cell = new Cell();

var minLimit:uint = 1;
var maxLimit:uint = 50;
var range:uint = maxLimit - minLimit;
var p:Number = Math.ceil(Math.random()*range) + minLimit;

for (p; p < maxLimit; p += 1)
{
    addChild(myCell);
    myCell.x = xp
    myCell.y = xp
    myCell.scaleX = 6
    myCell.scaleY = 6

    var xminLimit:uint = 100;
    var xmaxLimit:uint = 400;
    var xrange:uint = xmaxLimit - xminLimit;
    var xp:Number = Math.ceil(Math.random()*xrange) + xminLimit;



}
Was it helpful?

Solution

You need to move the instance creation code (var myCell:Cell = new Cell();) inside the loop to create maxLimit number of instance instead you are creating only one instance outside the loop.

Try this,

var minLimit:uint = 1;
var maxLimit:uint = 50;
var range:uint = maxLimit - minLimit;
var p:Number = Math.ceil(Math.random()*range) + minLimit;

for (p; p < maxLimit; p += 1)
{
    var myCell:Cell = new Cell();
    var xminLimit:uint = 100;
    var xmaxLimit:uint = 400;
    var xrange:uint = xmaxLimit - xminLimit;
    var xp:Number = Math.ceil(Math.random()*xrange) + xminLimit;
    addChild(myCell);
    myCell.x = xp
    myCell.y = xp
    myCell.scaleX = 6
    myCell.scaleY = 6        

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top