【发布时间】: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...)。另外值得注意的是,玩家的位置不受数组的限制,我只是将它移动到我希望它移动的像素量。
提前致谢!
【问题讨论】: