简体   繁体   中英

Javascript canvas, collision detection via array not working

Basically, I have a program that makes a square, and stores the left, right, top and bottoms in an array. When it makes a new square, it cycles through the array. If the AABB collision detection makes the new square overlap with another square, it should make sure that the square is not displayed, and tries again. Here is a snippet of the code I made, where I think the problem is:

var xTopsBotsYTopsBotsSquares = [];

//Makes a randint() function.
function randint(min, max) {

    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function checkForOccupiedAlready(left, top, right, bottom) {

    if (xTopsBotsYTopsBotsSquares.length == 0) {

        return true;
    }
    for (i in xTopsBotsYTopsBotsSquares) {
        if (i[0] <= right || i[1] <= bottom ||
            i[2] >= left || i[3] >= top) {/*Do nothing*/} 
        else {

            return false;
        }
    }

    return true;
}

//Makes a new square
function makeNewsquare() {
    var checkingIfRepeatCords = true;

    //DO loop that checks if there is a repeat.
    do {
        //Makes the square x/y positions 
        var squareRandomXPos = randint(50, canvas.width - 50);
        var squareRandomYPos = randint(50, canvas.height - 50);

        //Tests if that area is already occupied
        if (checkForOccupiedAlready(squareRandomXPos, 
                                    squareRandomYPos, 
                                    squareRandomXPos+50, 
                                    squareRandomYPos+50) == true) {

            xTopsBotsYTopsBotsSquares.push([squareRandomXPos, 
                                            squareRandomYPos, 
                                            squareRandomXPos+50, 
                                            squareRandomYPos+50]);

            checkingIfRepeatCords = false;

        }
    }
    while (checkingIfRepeatCords == true);

}

Any help is much appreciated.

Your loop is incorrect I think, since you use i as a value, whereas it is a key:

for (i in xTopsBotsYTopsBotsSquares) {
    if (i[0] <= right || i[1] <= bottom ||
        i[2] >= left || i[3] >= top) {/*Do nothing*/} 
    else {

        return false;
    }
}

Could become:

for (var i = 0, l < xTopsBotsYTopsBotsSquares.length; i < l; i++) {
    var data = xTopsBotsYTopsBotsSquares[i];

    if (data[0] <= right || data[1] <= bottom ||
        data[2] >= left  || data[3] >= top) {/*Do nothing*/} 
    else {

        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM