Java:迭代找到一个尚未使用的坐标点?

时间:2016-02-19 14:07:37

标签: java random coordinates top-down

我使用以下方法尝试找到以前没有使用过的点(坐标),并且不在以前使用过的坐标和坐标的范围内。

它的工作方式是我渲染"基地" (RTS自上而下的游戏),我正在为x和y创建两个随机变量位置。我将这些以及基础纹理传递给以下方法。该方法循环遍历每个先前渲染的基础的矩形的矩形列表。如果该点在任何矩形内,则使用不同的坐标集再次调用该方法。这样做直到找到一个不在矩形内的集合。然后,它会在这些坐标处向列表中添加一个新矩形,并返回它们,以便游戏可以渲染新的基础。

然而,基数仍然重叠。

以下是方法:

private Point getCoords(int x, int y, Texture t){
    for (int i=bases.size()-1; i> -1; i--) {
        if (bases.get(i).contains(new Point(x,y))){
            x = new Random().nextInt(map.getWidth() * map.getTileWidth());
            y = new Random().nextInt(map.getHeight() * map.getTileHeight());
            getCoords(x, y, t);
        }
    }
    bases.add(new Rectangle(x,y,t.getImage().getWidth(), t.getImage().getHeight()));
    return new Point(x, y);
}

以下是它被称为的地方:

switch(ran){
            default:
                int x = new Random().nextInt(map.getWidth() * map.getTileWidth());
                int y = new Random().nextInt(map.getHeight() * map.getTileHeight());
                Point p = getCoords(x, y, temp);
                map.generateBase("air", p.x, p.y);
                break;
        }

这里有什么问题吗?

由于

3 个答案:

答案 0 :(得分:1)

            int x = new Random().nextInt(map.getWidth() * map.getTileHeight());

可能是一个糟糕的复制粘贴。它可能是:

            int x = new Random().nextInt(map.getWidth() * map.getTileWidth());

在两个代码中:-D

答案 1 :(得分:1)

有几个问题:

  • 您的算法可能会覆盖错误坐标的好坐标(免费坐标),如果您找到一个好地方,则没有任何条件退出循环/递归

  • 您正在检查矩形是否包含该点,但稍后您要添加一个矩形,因此它可能不包含该点,但稍后创建的矩形可能会发生碰撞

试试这个

private Point getCoords(int x, int y, Texture t){
    boolean found = false;
    final int width = map.getTileWidth();
    final int height = map.getTileHeight();
    while(!found) {
            x = new Random().nextInt(map.getWidth() * width);
            y = new Random().nextInt(map.getHeight() * height);
            for (int i=bases.size()-1; i> -1; i--) {
                if (!bases.get(i).intersects(new Rectanble(x,y, width, height))){
                        found = true;
                } else found = false;
            }
    }

        bases.add(new Rectangle(x,y,t.getImage().getWidth(), t.getImage().getHeight()));
        return new Point(x, y);
}

***编辑:我不确定是否必须使用TileWidth和TileHeight或widthheight的图像宽度和图像高度:D

答案 2 :(得分:0)

好的,经过一些游戏,我发现问题是保存的矩形是用固定的位置保存的,这意味着当地图移动时,矩形不会。修复是遍历每个基地并获得基地的地图位置,而不是屏幕位置,并检查这一点。此外,我发现我正在检查矩形中的一个点,这个点可能在矩形之外,但仍然使我的碱基重叠。所以我现在检查矩形 - 矩形碰撞

相关问题