-2

I'm currently writing an algorithm to generate map-like islands for a procedural generation project. Part of my display code takes the float height (a value between 0 and 1) and clamps it to a specific 0.05 value in order to generate contours rather than continuous changes in height.

Here is my very long if else statement:

float newHeight;

if (height > 0.0 && height <= 0.05) {
    newHeight = 0.05;
} else if (height > 0.05 && height <= 0.1){
    newHeight = 0.1;
} else if (height > 0.1 && height <= 0.15){
    newHeight = 0.15;
} else if (height > 0.15 && height <= 0.2){
    newHeight = 0.2;
} else if (height > 0.2 && height <= 0.25) {
    newHeight = 0.25;
} else if (height > 0.25 && height <= 0.3) {
    newHeight = 0.3;
} else if (height > 0.3 && height <= 0.35) {
    newHeight = 0.35;
} else if (height > 0.35 && height <= 0.4) {
    newHeight = 0.4;
} else if (height > 0.4 && height <= 0.45) {
    newHeight = 0.45;
} else if (height > 0.45 && height <= 0.5) {
    newHeight = 0.5;
} else if (height > 0.5 && height <= 0.55){
    newHeight = 0.55;
} else if (height > 0.55 && height <= 0.6){
    newHeight = 0.6;
} else if (height > 0.6 && height <= 0.65){
    newHeight = 0.65;
} else if (height > 0.65 && height <= 0.7){
    newHeight = 0.7;
} else if (height > 0.7 && height <= 0.75){
    newHeight = 0.75;
} else if (height > 0.75 && height <= 0.8){
    newHeight = 0.8;
} else if (height > 0.8 && height <= 0.85){
    newHeight = 0.85;
} else if (height > 0.85 && height <= 0.9){
    newHeight = 0.9;
} else if (height > 0.9 && height <= 0.95){
    newHeight = 0.95;
} else if (height > 0.95) {
    newHeight = 1.0;
} else {
    newHeight = 0.0;
}

It runs as part of a function that iterates through the array of height values. I'm rather new to C++ and programming in general but so far have not been able to find anything that pertains to this particular problem on stackoverflow. There must be a better way to do this as adding n extra "contours" would be truly unfeasible.

Any input would be greatly appreciated! Thanks.

GomiNoSensei
  • 403
  • 5
  • 11

1 Answers1

0

You may want to check out a lookup table:

+-------+-------+-------+  
| lower | upper |  new  |  
| bound | bound |height |  
+-------+-------+-------+  

You make an array of these.
If height is in the range, then use the new height from the same entry.

if ((height > table[i].lower_bound) && (height <= table[i].upper_bound))
{
  height = table[i].new_height;
  break; // out of loop.
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154