Joel
Joel

Reputation: 247

AS3 - hitTestObject with dynamic MovieClips added through For Loops

I've been attempting to set up a hitTestObject function in a project I've been working on recently and have encountered some difficulty.

This is because I'm trying to do it with MovieClip instances dynamically added through a For Loop. The MovieClips being added are called 'square' and when I left Mouse Click I add a series of these MovieClips to the stage. My problem is that I want to listen out for a hitTestObject of 'square' intercepting 'square' and subsequent additions of the same MovieClip.

I've set up a numerical variable that increments up by 1 each time I add the group of 'square' MovieClips through left click to the stage and I've assigned this number along with a string to combine together to create a square.name instance.

In my case the first group of MovieClips added would have a .name instance called 'Square 1' and then 'Square 2' on the second mouse click and so on.

I've also added and pushed each name through into a container array for referencing later.

So how can I actually reference these dynamic names in a hitTestObject argument using my .name instance and array??

I'm sure it is obvious and I've done the groundwork so any help to point this out to me would be greatly appriciated.

Many Thanks.

Upvotes: 2

Views: 1324

Answers (1)

dezza
dezza

Reputation: 123

Here is a possible way assuming you are trying to do this in the timeline and you have a MovieClip subclass in the library called 'Square'. Beware of modifying the array while the hitTests are being performed. If you want to remove squares, wait till after all tests have completed, or make a copy of the squares array.

var squares: Array = [];

function addSquares(n: int): void {
    var square: MovieClip;

    for (var i: int = 0;
    i < n;
    i++) {
        square = new Square();
        square.name = "square" + i;
        addChild(square);
        squares.push(square);
    }
}


function checkHits(): void {
    var square: MovieClip;
    var checkSquare: MovieClip;

    for (var i: int = 0;
    i < squares.length;
    i++) {
        square = squares[i];

        for (var j: int = i + 1;
        j < squares.length;
        j++) {
            checkSquare = squares[j];

            if (square.hitTestObject(checkSquare)) {
                squaresHit(square, checkSquare);
            }
        }
    }
}


function squaresHit(square1, square2): void {
    // do something
    trace("squaresHit:" + square1.name + "," + square2.name);
}


addSquares(4);
checkHits();

//squaresHit:square0,square1
//squaresHit:square0,square2
//squaresHit:square0,square3
//squaresHit:square1,square2
//squaresHit:square1,square3
//squaresHit:square2,square3

Upvotes: 0

Related Questions