检测到达图像的对象

时间:2016-06-16 15:04:31

标签: java android canvas

我是这个领域的新人,我有一个问题 -
我有一个图像和一个对象。让我们调用对象" ball" 球正在移动,并在某个时刻到达图像。这是我的问题 -
如何检测到球碰到了图像? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

您应该以某种数学方式对对象进行建模 - 例如作为闭合多边形。然后你可以搜索两个多边形交集的算法。

答案 1 :(得分:0)

如果您正在使用2D,您可以使用简单的Rectanlge碰撞检测。 基本上要检查一个矩形是否与另一个矩形相撞,你必须用它的宽度和高度来检查它的X和Y位置。

下面我有一个使用html5标签Canvas

的jsfiddle示例

jsfiddle:https://jsfiddle.net/e2dmef7q/

检查冲突的代码是

function Mathematics()
{

}

Mathematics.prototype.PointInRect = function(pnt_x, pnt_y, rect_x, rect_y, rect_w, rect_h)
{
    if ( (pnt_x >= rect_x) && (pnt_x <= rect_x + rect_w - 1) )
    {
        if ( (pnt_y >= rect_y) && (pnt_y <= rect_y + rect_h - 1) )
        {return true;}
    }
    return false;
}

Mathematics.prototype.RectToRectCollision = function(rect1_x, rect1_y, rect1_w, rect1_h,
                             rect2_x, rect2_y, rect2_w, rect2_h)
{
    // top-left corner
    if ( this.PointInRect(rect1_x, rect1_y, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
    // top-right corner
    if ( this.PointInRect(rect1_x + rect1_w - 1, rect1_y, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
    // bottom-right corner
    if ( this.PointInRect(rect1_x + rect1_w - 1, rect1_y + rect1_h - 1, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
    // bottom-left corner
    if ( this.PointInRect(rect1_x, rect1_y + rect1_h - 1, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
    // Check to see if rectangle 2 is hit any part of rectanlge 1
    // top-left corner
    if ( this.PointInRect(rect2_x, rect2_y, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
    // top-right corner
    if ( this.PointInRect(rect2_x + rect2_w - 1, rect2_y, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
    // bottom-right corner
    if ( this.PointInRect(rect2_x + rect2_w - 1, rect2_y + rect2_h - 1, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
    // bottom-left corner
    if ( this.PointInRect(rect2_x, rect2_y + rect2_h - 1, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
    // If there is no collision
    return false;
}

快速向下运行RectToRectCollision获取两个矩形的x,y,宽度和高度。然后使用PointInRect函数检查矩形的一个点是否在另一个矩形内。

P.S。我提供的代码来自我的一个旧例子,它看起来有点可怕。但Mozilla网站提供了有关2D碰撞的一些很好的信息https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection