繁体   English   中英

Javascript画布,无法通过数组进行冲突检测

[英]Javascript canvas, collision detection via array not working

基本上,我有一个制作正方形的程序,并将左,右,顶部和底部存储在一个数组中。 当它变成一个新的正方形时,它将在数组中循环。 如果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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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