【问题标题】:Java 2D array, possible to set individual size?Java 2D数组,可以设置单独的大小吗?
【发布时间】:2017-04-29 14:28:29
【问题描述】:

关于 Java 2D 数组的快速问题;对于基于图块的自上而下的 2D 游戏(使用摇摆),我使用 一个二维数组来创建一个地图,像这样

public int[][] createMap(){
    return new int[][]{
    {0, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}};
}

然后我在我的 gameComponents 类中使用它,在该类中我将各个图块绘制到地图上,就像这样

protected void paintComponent(Graphics g){
  super.paintComponent(g);

  for (int row = 0; row < game.getMap().getWidth(); row++) {
      for (int col = 0; col < game.getMap().getHeight(); col++) {
         g.drawImage(tile.getTileImage().get(values()[game.getMap().getMapArray()[col][row]]), row * SIZE,
            col * SIZE, this);
    }

} }

(其中 size 是图块的大小)
这有效,并且它按预期正确地将每个图块绘制到地图上,但是 这也会导致碰撞检测问题。正如您可能已经注意到的,虽然我确实在 draw 方法中定义了图块之间的大小,但它根本没有在数组中定义。正如您想象的那样,在检查碰撞时会引发问题,因为绘制的图块不在 2D 数组中的图块所在的位置(由于大小偏移)。

这是我用于检查碰撞的代码(当然,由于 ArrayIndexOutofbounds 无法正常工作)。

    public boolean collisionDetected(int xDirection, int yDirection, Game game, Player player){
      for (int row = 0; row < game.getMap().getHeight() * 16; row ++){
        for (int col = 0; col < game.getMap().getWidth() * 16; col++) {
          System.out.println(col + xDirection + player.getPositionX());
          if(game.getMap().getTile(col + xDirection + player.getPositionX() ,
               row + yDirection + player.getPositionY()) == Tiles.GRASS ){
            System.out.println("COLLISION DETECTED");
            return true;
    }
    }
}

return false;
}

此方法使用地图类中的一个方法,该方法返回该地图上的图块 具体坐标,像这样

public Tiles getTile(int col,int row){
    return Tiles.values()[mapArray[col][row]];
}

当然,由于二维数组不知道大小偏移,它只是抛出 一个数组索引出界。
我的问题是,是否可以在考虑到图块大小的情况下定义 2D 地图数组?我很感激我能得到的任何帮助和意见,毕竟我是来学习的!

额外说明:所有图块都在一个枚举类中(即 AIR、GRASS、STONE...)。另外值得注意的是,玩家的位置不受数组的限制,我只是将它移动到我希望它移动的像素量。

提前致谢!

【问题讨论】:

    标签: java arrays swing


    【解决方案1】:

    此方法使用地图类中的一个方法,该方法返回该特定坐标上的图块,如下所示

    public Tiles getTile(int col,int row){
        return Tiles.values()[mapArray[col][row]];
    }
    

    那么如果你有一个“坐标”,为什么要调用参数col/row?

    如果你有一个 10x10 的网格并且每个图块是 20 像素,那么网格大小是 200x200,所以你可以有 0-199 范围内的 x/y 值

    因此,如果您的坐标为 25x35,您只需将行/列值计算为:

    int row = 35 / 20;
    int column = 25 / 20;
    

    所以你的方法应该是这样的:

    public Tiles getTile(int x, int y)
    {
        int row = y / 20;
        int column = x / 20;
    
        return Tiles.values()[mapArray[row][column]];
    }
    

    【讨论】:

    • 谢谢!这很有意义;-)
    猜你喜欢
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2016-04-16
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多