我试图在我的游戏中实现Heightmaps,所以现在我已经制作了几种方法,但它们太慢了,而且,高度返回的数字像1.463563298e14! 如何从高度图上的像素获得介于0和1之间的值? 这些是我的方法:
public void setupHeights() {
int pixWidth = heightfile.getWidth();
int pixHeight = heightfile.getHeight();
int w = pixWidth;
int h = pixHeight;
this.heights = new float[w][h];
boolean countWidth = true;
for (int z = 0; z < pixHeight; z++) {
depth++;
for (int x = 0; x < pixWidth; x++) {
if (countWidth)
width++;
int height;
if (whiteHigh) {
height = 256 - (-1 * heightfile.getRGB(x, z));
} else {
height = -1 * heightfile.getRGB(x, z);
}
heights[x][z] = height;
numPoints++;
}
countWidth = false;
}
System.out.println("Heights have been set up!");
}
@Override
public void update() {
if (!this.hasWorldObj())
return;
if (heightfile!=null) {
for (Entity e : entities) {
if (e != null && !(e.posX < pos.getX() || e.posZ < pos.getZ() || e.posX > pos.getX() + 1
|| e.posZ > pos.getZ() + 1)) {
{
if (heightfile != null) {
double localX = Math.abs(pos.getX() - e.posX);
double localZ = Math.abs(pos.getZ() - e.posZ);
int x = (int) (localX * width);
int y = (int) (localZ * depth);
e.posY = pos.getY() + getHeight(x, y);
}
}
} else
e = null;
}
}
}
public float getHeight(float xf, float zf) {
int x = worldCoordToIndex(xf);
int z = worldCoordToIndex(zf);
System.out.println("getting height for: " + x + ", " + z);
if (x < 0)
x = 0;
if (z < 0)
z = 0;
if (z >= heights.length) {
System.out.println("WARN getHeight z index out of bounds: " + z);
z = heights.length - 1;
}
if (x >= heights[z].length) {
System.out.println("WARN getHeight x index out of bounds: " + x);
x = heights[z].length - 1;
}
System.out.println("Returned height: " + heights[z][x] * heightScale);
return heights[z][x] * heightScale;
}
private int worldCoordToIndex(float f) {
return (int) Math.floor(f / widthScale);
}