有关Java 2D数组的快速问题;对于我的基于图块的,自上而下的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;
}
此方法使用map类中的方法,该方法返回该图块上的图块
特定坐标,像这样
public Tiles getTile(int col,int row){
return Tiles.values()[mapArray[col][row]];
}
而且,当然,由于2D数组不知道大小偏移量,因此它只会抛出
arrayindexoutofbound。
我的问题是,是否有可能考虑瓷砖的大小来定义2D地图数组?感谢您能获得的任何帮助和投入,毕竟我是来这里学习的!
额外说明:所有磁贴都属于枚举类(即AIR,GRASS,STONE ...)。同样值得一提的是,玩家的位置不受数组限制,我只是将其移动想要移动的像素数量。
提前致谢!
最佳答案
此方法使用map类中的一种方法,该方法返回该特定坐标上的图块,如下所示
public Tiles getTile(int col,int row){
return Tiles.values()[mapArray[col][row]];
}
因此,如果您有一个“坐标”,为什么还要调用参数col / row?
如果您有10x10的网格,且每个图块为20像素,则网格大小为200x200,因此x / y值的范围为0-199
因此,如果坐标为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]];
}