Java 2D多边形 - 多边形碰撞检测

时间:2015-05-13 14:06:16

标签: java math collision-detection polygon

最近我一直在使用Polygon类来制造小行星以及子弹和宇宙飞船。我目前正在尝试为程序创建碰撞检测,但似乎碰撞检测仅在1/5的时间内工作(没有出现模式为什么它起作用)。

这是代码.. 创建多边形:

SELECT wp_posts.*,MONTH(wp_posts.man_date) as month 
FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_term_taxonomy 
ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
 INNER JOIN wp_locations 
ON (wp_posts.ID = wp_locations.post_id) 
WHERE wp_term_taxonomy.taxonomy = 'tipo_manifestazione'
AND wp_term_taxonomy.term_id = 97 AND wp_posts.post_type = 'manifestazione' AND MONTH(wp_posts.man_date) = 4 
AND wp_posts.post_status = 'publish' 
AND wp_posts.vip = 'NULL' 
AND wp_locations.continente LIKE '%Brescia%' 
OR wp_locations.nazione LIKE '%Brescia%' 
OR wp_locations.regione LIKE '%Brescia%' 
OR wp_locations.citta LIKE '%Brescia%' 
OR wp_locations.luogo LIKE '%Brescia%' 
GROUP BY wp_posts.ID 
ORDER BY wp_posts.ID DESC

旋转并移动多边形:

void renderPoly() {   
    int j;
    int s = sides;
    double r, angle;
    int x, y;

    for (j = 0; j < s; j++) {
        angle = 2 * Math.PI / s * j;
        r = MIN_ROCK_SIZE + (int) (Math.random() * (MAX_ROCK_SIZE - MIN_ROCK_SIZE));
        x = (int) (r * Math.cos(angle));
        y = (int) (r * -Math.sin(angle));

        cOM[0] += x;
        cOM[1] += y;
        pointData[j][0] = x;
        pointData[j][1] = y;
    }

    cOM[0] /= asteroidShape.npoints;
    cOM[1] /= asteroidShape.npoints;

    for (int i = 0; i < asteroidShape.npoints; i++) {
        pointData[i][0] += cOM[0];
        pointData[i][1] += cOM[1];
    }    
}

检查是否触摸子弹:

void move() {    
    int x, y, i;
    //change rotation
    theta += rotVel;

    //change x
    asteroidData[0] += deltaX;

    //change y
    asteroidData[1] += deltaY;

    for (i = 0; i < asteroidShape.npoints; i++) {

        x = (int) (pointData[i][0] * Math.cos(theta) - pointData[i][1] * Math.sin(theta) );
        y = (int) (pointData[i][0] * Math.sin(theta) + pointData[i][1] * Math.cos(theta) );

        asteroidShape.xpoints[i] = x + asteroidData[0];
        asteroidShape.ypoints[i] = y + asteroidData[1];

        asteroidShape.invalidate();
    }
}

(除了构造函数需要一个ship对象之外,ship方法是相同的)

以及在“游戏”类中调用它的循环:

    boolean hitBullet(Bullet b) {
    this.asteroidShape.invalidate();
    for (int i = 0; i < b.bulletShape.npoints; i++) 
        if (this.asteroidShape.contains(b.bulletShape.xpoints[i], b.bulletShape.ypoints[i]) )
            return true;

    for (int j = 0; j < this.asteroidShape.npoints; j++)
        if (b.bulletShape.contains(this.asteroidShape.xpoints[j], this.asteroidShape.ypoints[j]) )
            return true;

    return false;

}

我一直在寻找替代解决方案,例如分离轴定理,但我有时会有凸多边形,因为这个方法(.contains())已经存在,我想使用它。

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

我发现解决此问题的简便方法是将Shapes(在您的情况下为Polygon(2D?))转换为Areas。您可以使用Area.intersect(Area)查看两个区域是否发生冲突