Question

How to reference another instance of the same class? None of them have any names, as they are generated through code. A random amount of instances are generated each time. I need to compare them. Thanks.

This is the code I have on the timeline (which generates the instances).

var minLimit:uint = 1;
var maxLimit:uint = 10;
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 = 300;
    var xrange:uint = xmaxLimit - xminLimit;
    var xp:Number = Math.ceil(Math.random()*xrange) + xminLimit;
    addChild(myCell);
    myCell.x = xp
    myCell.y = xp
    myCell.scaleX = 3
    myCell.scaleY = 3        

}


var listOfCells:Array = new Array();

for (var i:int =0; i < (root as MovieClip).numChildren; i++)
{
    listOfCells.push((root as MovieClip).getChildAt(i));
}

trace(listOfCells)

var len:int = listOfCells.length;
for (var j:int =0; j < len; j++)
{
    trace(listOfCells[j].x);
}


trace("Cells on stage: " + Cell.count);

The game cenerates a random number of cells. In order to code so they sometimes go closer and inspect each other, I need to know how to compare them. Example, code I could put in the class - like: If this.x < OTHER(of the same class).x So I can compare two different instances within the same class.

Was it helpful?

Solution

To compare the cells and have them move towards each other if they are below 200px apart (for example):

var maxDistance: Number = 200;
var minDistance: Number = 20;

var len:int = listOfCells.length;
for (var j:int =0; j < len; j++)
{
    var cell: Cell = listOfCells[j];
    for(var k:int = 0; k < len; k++)
    {
        var cellToCompare = listOfCells[k];
        if(cellToCompare != cell) {
            var dx: Number = cellToCompare.x - cell.x;
            var dy: Number = cellToCompare.y - cell.y;
            var distance : Number = Math.sqrt(dx * dx + dy * dy);
            if(distance < maxDistance && distance > minDistance) {
                cell.x = cell.x + dx * 0.1;
                cell.y = cell.y + dy * 0.1;
            }
        }
    }
}

Also to be sure the array only contains Cell instances, use the 'is' operator:

var listOfCells:Array = new Array();
for (var i:int =0; i < (root as MovieClip).numChildren; i++)
{
    var child: DisplayObject = (root as MovieClip).getChildAt(i);
    if(child is Cell) {
        listOfCells.push(child);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top