光线投射算法中连接光线的问题

时间:2015-08-20 16:54:22

标签: java algorithm raycasting

我正在研究一种简单的光线投射算法,我可以将其用于我想要制作的未来游戏中的2D阴影。我已经找到了光线投射部分,但问题是当我真的想要绘制阴影时。

我知道绘制阴影涉及从每个投射光线的端点创建一个多边形,并从一个"阴影蒙版"中减去它的区域,这样你才能看到它中的内容。多边形的区域。但是,我的问题是我无法弄清楚我应该如何对光线进行排序,以便多边形形成合适的形状,而不是连接到随机光线。

我得到的是这样的事情。

Improperly connected polygon.

因此,如果熟悉光线投射的人能够确切地告诉我我应该如何以正确的顺序连接光线以获得正确的形状,我会很感激。重要的是,这是我的算法。

private void raycast(Point2D.Double target) {
    double theta = Math.atan2((target.y - mousePos.y), (target.x - mousePos.x));
    Point2D.Double currLoc = new Point2D.Double(mousePos.x, mousePos.y);
    boolean validRay = true;

    while(validRay) {
        double x = currLoc.x + Math.cos(theta);
        double y = currLoc.y + Math.sin(theta);

        // Check to see if the ray has gone out of the window.
        if((x < 0) || (x >= Game.WIDTH) || 
           (y < 0) || (y >= Game.HEIGHT)) {
            validRay = false;
        }

        // Check to see if the ray has collided with an object.
        for(Polygon c : obstacles) {
            if(c.contains(new Point2D.Double(x, y))) {
                validRay = false;
            }
        }

        if(validRay) {
            currLoc.x = x;
            currLoc.y = y;
        }
    }

    rays.add(new Point2D.Double(currLoc.x, currLoc.y));
}

目前我正在将光线连接成多边形。

if(rays.size() > 0) { // Create the shadow mask.
    BufferedImage overlay = new BufferedImage(Game.WIDTH, Game.HEIGHT, BufferedImage.TYPE_INT_ARGB);
    Graphics2D og2d = overlay.createGraphics();
    og2d.setColor(new Color(0.0f, 0.0f, 0.0f, 1.0f));
    og2d.clearRect(0, 0, Game.WIDTH, Game.HEIGHT);

    // Create a polygon from the endpoints of all the rays.
    Path2D.Double mask = new Path2D.Double();
    mask.moveTo(rays.get(0).x, rays.get(0).y);
    for(Point2D.Double end : rays) {
        mask.lineTo(end.x, end.y);
    }
    mask.closePath();

    og2d.setColor(Color.WHITE);
    og2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OUT, 0.0f));
    og2d.fill(mask);

    g2d.drawImage(overlay, 0, 0, null);
} // End creation of shadow mask.

有人可以给我一些帮助吗?

1 个答案:

答案 0 :(得分:1)

我设法通过使用端点和光源本身之间的角度作为排序标准来“排序”端点。基本上,最低角度位于列表的前面,依此类推。

现在唯一的问题是我在某些顶点上没有实际的端点,因为如果算法没有碰到对象本身直到它碰到屏幕的边缘,算法将继续经过顶点,所以当我连接顶点以制作多边形,它采用“快捷方式”。这是一个截图,以说明我的意思。

Improperly connected polygon

相关问题