Blub Blub - 4 months ago 14
Java Question

Perlin noise not generating number between 1 and -1

I'm developing a game in Java using LibGDX and I wanted random terrain generation. I found a Perlin class online and decided to use it for my project.

I currently have a simple world class with this as constructor:

public World() {
Random rand = new Random();
seed = rand.nextInt();
Perlin perlin = new Perlin(seed);

for(int x = 0; x < map.length; x++) {
for(int y = 0; y < map.length; y++) {
map[x][y] = perlin.noise2(x, y);
}
}
}


(map is a 2d float array ofcourse)

In my game's main class I create a world and then draw it in the render() method like this:

batch.begin();
for (int x = 0; x < w.getMap().length; x++) {
for (int y = 0; y < w.getMap().length; y++) {
if (w.getMap()[x][y] <= 0) {
batch.draw(water, x * 32, y * 32);
}
if (w.getMap()[x][y] > 0) {
batch.draw(grass, x * 32, y * 32);
} else {
log.severe("not between -1 and 1"); }
}
}
batch.end();


Upon execution it basically spams the console with "not between -1 and 1" and after some time the screen fills up with water texture.

Is it the class or am I messing up? Probably the latter. How should I fix it? Also, any tips on optimizing? Code kinda looks messy right now.

This is the class I'm using. Posted it on pastebin because it's ~580 lines long.

Answer

Well, I think the obvious one is that your else-if logic is off, you're using two if statements in a row:

    if (w.getMap()[x][y] <= 0) {
        batch.draw(water, x * 32, y * 32);
    }
    if (w.getMap()[x][y] > 0) {
        batch.draw(grass, x * 32, y * 32);
    } else {
        log.severe("not between -1 and 1");             }
    }

The bracket alignment is also a bit iffy, but try using if else if else:

    if (w.getMap()[x][y] <= 0) {
        batch.draw(water, x * 32, y * 32);
    } else if (w.getMap()[x][y] > 0) {
        batch.draw(grass, x * 32, y * 32);
    } else {
        log.severe("not between -1 and 1");
    }

Previously anything below 0 would've printed that error.