0

I am preparing a game development plan for my next phonegap app. I am specific thinking about collision detection.

My thought so far are. The different screen sizes on the different smartphones will make it impossible or ?

If a game area is 500px x 500px.

if( collision left wall ) {
  // deny access further
}

if( collision right wall ) {
  // deny access further
}

if( collision top wall ) {
  // deny access further
}

if( collision bottom wall ) {
  // deny access further
}

Lets assume that "collision left wall" is 0px and "collision right wall" is 500px as normal.

I have a trouble with the understanding of the dynamic screen sizes on smartphones, how do i solve this problem?

1) Do i need to calculate the dynamic screen size and scale my images, game area and so forth?

2) Is there a much more smart way to solve this problem?

Thanks :-)

4

1 回答 1

2

您需要计算碰撞检测的实际边界矩形位置。

var element1 = (document.getElementById('element1-id'));
var rect1 = element1.getBoundingClientRect();

然后得到它的宽度、高度、左侧和顶部位置

var left1= rect1.left;
var top1= rect1.top;
var width1= rect1.width;
var height1= rect1.Height;

然后获取另一个对象(该元素将在其上发生碰撞的对象)的属性:

var element2 = (document.getElementById('element2-id'));
var rect2 = element2.getBoundingClientRect();

现在获取它的宽度、高度、左侧和顶部位置

var left2= rect2.left;
var top2= rect2.top;
var width2= rect2.width;
var height2= rect2.Height;

现在是检查碰撞的时候了:在代码中粘贴以下方法:

function bounding_box_collision(b1_x, b1_y, b1_w, b1_h, b2_x, b2_y, b2_w, b2_h) {
    if ((b1_x > b2_x + b2_w - 1) || // is b1 on the right side of b2?
        (b1_y > b2_y + b2_h - 1) || // is b1 under b2?
        (b2_x > b1_x + b1_w - 1) || // is b2 on the right side of b1?
        (b2_y > b1_y + b1_h - 1)
        ) // is b2 under b1?
    {
// no collision
        return "No";
    }
    else// collision
    {
        return "Yes";
    }


}

现在运行一个设置的间隔并在所需的持续时间检查碰撞,为了平滑的碰撞检测,总是使用小的持续时间,如下面的代码:

setInterval(function(){
     if(( bounding_box_collision(left1, top1, width1, height1, left2, top2, width2,      height2))=="Yes"){
         console.log("Collision Detected");
    }else{
         console.log("No Collision");
    }

},0)//0 milliseconds
于 2013-10-01T13:19:08.537 回答