简体   繁体   中英

Bug in collision detecting algorithm, Javascript

OK so I'm making a 2D platform game in JavaScript and for my collision detecting I have 2 types of objects: game objects which are detected by focus areas and focus areas; which detect the objects both have 4 coordinates which form a box x1 and y1 are the left/top and x2 and y2 are the left/bottom

the game object's box coordinates are unchanging numbers which must be calculated to be relative to the game objects position whereas the focus areas coordinates are updated to be the exact spots

my problem is for some reason when this code (below) comes across a focus area that is smaller than the game object (in coordinates) it goes undetected unless the focus area conflicts with the upper-left pixel of the game object's box, how do I fix this? (by the way this is all in a double 'for loop')

            var O_x=game.objects[ii].phy.pos.x,
                O_aur_x_1=game.objects[ii].col.aur.x1,
                O_aur_x_2=game.objects[ii].col.aur.x2,

                F_x_1=game.focusAreas[i].x1,
                F_x_2=game.focusAreas[i].x2,

                O_y=game.objects[ii].phy.pos.y,
                O_aur_y_1=game.objects[ii].col.aur.y1,
                O_aur_y_2=game.objects[ii].col.aur.y2,

                F_y_1=game.focusAreas[i].y1,
                F_y_2=game.focusAreas[i].y2;


        if      ( (O_x + O_aur_x_1) >= F_x_1 && (O_x + O_aur_x_1) <= F_x_2 || F_x_1 >= (O_x + O_aur_x_1) && F_x_1 <=(O_x + O_aur_x_2))
        {// if object's x1 is within xfocus range
        }
        else if ( (O_x + O_aur_x_2) >= F_x_1 && (O_x + O_aur_x_2)<= F_x_2  || F_x_2 >= (O_x + O_aur_x_1) && F_x_1 <=(O_x + O_aur_x_2))
        {// if object's x2 is within xfocus range
        }
        else{continue;}

        if      ( (O_y + O_aur_y_1) >= F_y_1 && (O_y + O_aur_y_1) <= F_y_2 || F_y_1 >= (O_y + O_aur_y_1) && F_y_1 <=(O_y + O_aur_y_2))
        {// if object's y1 is within yfocus range
        }
        else if ( (O_y + O_aur_y_2) >= F_y_1 && (O_y + O_aur_y_2) <= F_y_2 || F_y_2 >= (O_y + O_aur_y_1) && F_y_1 <=(O_y + O_aur_y_2))
        {// if object's y2 is within yfocus range
        }
        else{continue;}

Mind your parentheses!

JS uses C-style short-circuit evaluation, meaning:

  • if "a && b" then b is only evaluated, if a is true, the evaluation is exited as false as soon as any expression is false.
  • if "a || b" then b is only evaluated if a is false, the evaluation is exited as true as soon as any expression is true.

So you need an extra pair of brackets to group the expressions on both sides of the or-operator:

if ((ax1 >= bx1 && ax1 <= bx2) || (bx1 >= ax1 && bx1 <= ax2)) {
  // ...
}

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