1

I'm having some issue regarding collision detection in a game i am making. I have the distance between the two objects using this:

    double b1Dist = Math.sqrt((obOneX - obTwoX) * (obOneX - obTwoX)
            + ((obOneY - obTwoY) * (obOneY - obTwoY)));
    double b1DistTwo = b1Dist - objectOneRadius;
    b1DistFinal = b1DistTwo - objectTwoRadius;

and I was attempting to do collision detection with this:

  if (b1DistFinal <= objectOneRadius && b1DistFinal <= objectTwoRadius ) {
            return false;
        }
         else
            return true;

    }

I'm new to java so i'm sure theres probably much better/more efficient ways to write the above, however could anyone please help me out or point me in the right direction?

Thanks

4

1 回答 1

1

这样做的效率并没有什么问题。但是,如果obOneXobOneY等是对象中心的 x 和 y 坐标,则您的公式是错误的。

变量b1DistFinal是两个对象外边缘之间的距离。如果为零,则这些物体发生了碰撞。

尝试:

if (Math.abs(b1DistFinal) < 0.001) {
    return true;
} else {
    return false;
}

注意:我不是检查它是否完全为零,而是检查它是否接近零,以允许在双算术期间出现一些舍入误差。

于 2013-03-24T04:15:36.177 回答