This is supposed to draw a heightmap to the screen using isometric 3D (has not yet been optimized).
public class IsometricRenderer {
private int scaleFactor = 10;
private double xOrigin = 0;
private double yOrigin = 0;
private final double angle = 0.46365;
private final double a = Math.cos(angle);
private final double b = Math.sin(angle);
private int worldXToScreenX(double x, double y, double z)
{
int xC = (int) Math.round((x * scaleFactor - z * scaleFactor) * a);
int xS = (int) Math.round(xC + xOrigin * scaleFactor);
return xS;
}
private int worldYToScreenY(double x, double y, double z)
{
int yC = (int) Math.round((x * scaleFactor + z * scaleFactor) * b + y * scaleFactor);
int yS = (int) Math.round(-yC + yOrigin * scaleFactor);
return yS;
}
public double getScaleFactor()
{
return scaleFactor;
}
public void translateCam(double tx, double ty)
{
xOrigin += tx;
yOrigin += ty;
}
public void setCam(double x, double y)
{
xOrigin = x;
yOrigin = y;
}
private Point getScreenPoint(double x, double y, double z)
{
return new Point(worldXToScreenX(x, y, z), worldYToScreenY(x, y, z));
}
public void drawWorld(World w, Graphics2D g2)
{
for(int x = 0; x < w.width; x ++)
{
for(int z = 0; z < w.height; z ++)
{
int h = w.heightmap[x][z];
Point p = getScreenPoint(x, h, z);
int rightX = x + 1;
int frontZ = z - 1;
if(x >= w.width - 1)
rightX = x;
if(frontZ < 0)
frontZ = z;
Point right = getScreenPoint(x + 1, w.heightmap[rightX][z], z);
Point front = getScreenPoint(x, w.heightmap[x][frontZ], z - 1);
Point frontRight = getScreenPoint(x, w.heightmap[rightX][frontZ], z - 1);
g2.setColor(Color.gray);
/*
int[] xP = new int[]{p.x, right.x, frontRight.x, front.x};
int[] yP = new int[]{p.y, right.y + 1, frontRight.y, front.y};
g2.fillPolygon(xP, yP, xP.length);
g2.setColor(Color.black);*/
g2.drawLine(p.x, p.y, front.x, front.y);
g2.drawLine(p.x, p.y, right.x, right.y);
}
}
}
}
It works almost perfectly, but the lines are uneven:
Anyone spot the problem? According to some stuff I read online, the angle I used is supposed to make pretty lines.