Javascript画布,通过数组进行冲突检测不起作用

Javascript canvas, collision detection via array not working

本文关键字:冲突检测 不起作用 数组 画布 Javascript      更新时间:2023-09-26

基本上,我有一个程序,它可以制作一个正方形,并将左、右、顶部和底部存储在一个数组中。当它形成一个新的正方形时,它会在数组中循环。如果AABB碰撞检测使新的正方形与另一个正方形重叠,则应确保不显示该正方形,然后重试。以下是我制作的代码片段,我认为问题在于:

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);
}

非常感谢您的帮助。

我认为您的循环是不正确的,因为您使用i作为值,而它是一个密钥:

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

可能变成:

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;
    }
}