2016-04-14 81 views
0

我最近在stackoverflow上找到了代码,用于处理多边形和圆形之间的碰撞,它的工作原理。问题是因为我不太明白,所以如果有人能够给我简单的解释,我会很感激。libGDX多边形 - 圆形碰撞

// Check if Polygon intersects Circle 
private boolean isCollision(Polygon p, Circle c) { 
    float[] vertices = p.getTransformedVertices(); 
    Vector2 center = new Vector2(c.x, c.y); 
    float squareRadius = c.radius * c.radius; 
    for (int i = 0; i < vertices.length; i += 2) { 
     if (i == 0) { 
      if (Intersector.intersectSegmentCircle(new Vector2(
        vertices[vertices.length - 2], 
        vertices[vertices.length - 1]), new Vector2(
        vertices[i], vertices[i + 1]), center, squareRadius)) 
       return true; 
     } else { 
      if (Intersector.intersectSegmentCircle(new Vector2(
        vertices[i - 2], vertices[i - 1]), new Vector2(
        vertices[i], vertices[i + 1]), center, squareRadius)) 
       return true; 
     } 
    } 
    return false; 
} 

我没有得到它的部分是for循环。

+0

确保您检查圆形是否包含在多边形内。 http://stackoverflow.com/a/29938608/2900738 –

回答

1

intersectSegmentCircle有效地取一条线段(由前两个向量参数指定)和一个圆圈(由最后的向量和浮点参数指定),并且如果该线与圆相交,则返回true。

for循环循环遍历多边形的顶点(由于顶点由float[] vertices中的两个值表示,所以递增2)。对于每个顶点依次考虑通过将该顶点连接到多边形中的前一个顶点而形成的线段(即,它依次考虑多边形的每个边缘)。

如果intersectSegmentCircle找到该段的圆形交点,则该方法返回true。如果到最后找不到交点,则返回false。

for循环中的if/else仅用于第一个顶点 - 在这种情况下,“上一个”顶点实际上是float[] vertices中的最后一个顶点,因为多边形循环并将最后一个顶点连接回第一个顶点。

+0

谢谢你的时间:) – Emir