我知道标题不太有意义,但我想不出如何更好地表达,请耐心等待。
我正在使用java与LibGDX,我试图从保存的像素图加载数据来渲染屏幕上的地图。在像素图中,每个像素代表一个六边形的颜色(地图是六边形的网格)。
问题是:我正在从像素图加载数据(特别是颜色)到我称为HexInfo的类的数组。然而,当我将这个数组传递给另一个类以便在屏幕上绘制它时,数组中的每个HexInfo项的颜色都为黑色。以下是如何设置的
hexInfo = new HexInfo[cols][rows];
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
Color.rgba8888ToColor(color, savedScreenData.getPixel(i, j));
hexInfo[i][j] = new HexInfo(i,j);
hexInfo[i][j].setColour(color);
hexInfo[i][j].setIsVisible(true);
hexInfo[i][j].setIsOccupied(true);
//It is definitely set because this gives the correct colours
System.out.println(hexInfo[i][j].getColour());
}
}
mapScreen = new MapScreen(hexInfo);
这里^,屏幕上打印的getcolor是正确的。
然后,在MapScreen类中,我使用for循环来getcolor每个hexInfo:
public MapScreen(HexInfo[][] hexInfo)
{
cols = hexInfo.length;
rows = hexInfo[0].length;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
if (hexInfo[i][j].isOccupied())
System.out.println(hexInfo[i][j].getColour());
}
}
}
然而,这里每种颜色都是黑色。
HexInfo类如下:
public class HexInfo {
private Color colour;
private String owner;
private boolean isOccupied;
private boolean isVisible;
public Color getColour() {
return colour;
}
public String getOwner() {
return owner;
}
public boolean isOccupied() {
return isOccupied;
}
public boolean isVisible() {
return isVisible;
}
public void setIsOccupied(boolean isOccupied) {
this.isOccupied = isOccupied;
}
public void setColour(Color colour)
{
this.colour = colour;
System.out.println("SETTING COLOR IN HEXINFO AS: " + colour); //This also gives correct colour in sysout
}
public void updateOwner(Color color, String owner)
{
System.out.println("setting colour in hexinfo as " + color);
this.colour = color;
this.owner = owner;
isOccupied = true;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public HexInfo(int x, int y)
{
mapCoords = new Vector2(x,y);
colour = new Color(Color.BLACK);
isOccupied = false;
}
}
我已经检查过了,没有发现问题在哪里。如果它是与我的代码的其余部分,让我知道你需要什么其他信息(有很多,所以我显然没有包括所有的)。
这与将数组传递给构造函数无关。
当您调用setColour(...)
时, HexInfo
不会复制color
,它只是设置了一个引用。因此,数组的所有成员最终将指向相同的color
实例,因此它们都将具有您的最后一个像素的颜色。
像这样更改嵌套for循环的最内部部分应该可以修复它:
hexInfo[i][j] = new HexInfo(i,j);
hexInfo[i][j].setIsVisible(true);
hexInfo[i][j].setIsOccupied(true);
Color.rgba8888ToColor(hexInfo[i][j].getColour(), savedScreenData.getPixel(i, j));
//It is now *really* definitely set because this gives the correct colours
System.out.println(hexInfo[i][j].getColour());