简体   繁体   中英

Find the value of a 2D arrays neighbors?

I have a 2d array that generates terrain using perlin noise, and then places a (3D) block at a specific height - Before you click away, all I need help with is the 2D array that generates the "height-map". I am trying to figure out whether or not the block next to it is at the same elevation (if it is "neighboring" or not) by checking the values directly up, down, left, and right in the 2D array. If they are equal, then they are at the same elevation, and therefore "neighbors". if the problem that I am running into is that the check is always returning true for all the neighbors, even if the block has no neighbors.

A small example of the perlin noise height map

151514141312121111
151414131313121211
141414131312121211
141313131312121211
131313121212121111
131312121212111111
121212121111111111
111111111110101111
111111111010101111
111111111010101010
111111111010101010
101011101010101010
101010101099109999
991010109999988889
999109999888888999

and here is the checking code, you will have to see the entire file, linked below for context

      if (terrain[x][leftColumn] == terrain[x][z]) {
        neighbors[2] = true; // left side
      }
      if (terrain[x][rightColumn] == terrain[x][z]) {
        neighbors[3] = true; //right side
      }
      if (terrain[belowRow][z] == terrain[x][z]) {
        neighbors[4] = true; // front side (below)
      }
      if (terrain[aboveRow][z] == terrain[x][z]) {
        neighbors[5] = true; // back side (above)
      }    

Pastebin: https://www.pastiebin.com/5d5c5416391ec
any help is appreciated, Asher

Move this static variable initialization

boolean[] neighbors = new boolean[]{false, false, false, false, false, false};

inside the inner loop, where you check each block's neighbors, to instantiate a new neighbors array for each individual block. Right now neighbors is a static variable. You never reset the values on the neighbors array so it remains true after each iteration.

edit:

Also

  if (belowRow > 1) { 
    belowRowExists = false;
    belowRow = 0;
  } 
  if (rightColumn > - 1) { 
    rightColumnExists = false;
    rightColumn = 0;
  }

is wrong, you want to check if the column or row is out of bounds right? Then you want to see if they are >= chunkSize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM