2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ......

17
2D TERRAINS GENERATOR Santiago Yepes Serna Game Creator and Fan

Transcript of 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ......

Page 1: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

2D TERRAINS GENERATOR

Santiago Yepes SernaGame Creator and Fan

Page 2: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Project Information

More than a game this program was cre-ated with the aim to show a series of al-gorithms that generate different types of maps or terrains. Very useful if we want to create a 2D platform game, an RPG or maybe a click and point adventure.

Page 3: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Design

The overall design of this project was very simple. Using a tile map, and a sprite call "terrain". I´m going to fill the screen with differ-ent types of terrains using a Two dimensional Array(that I call "MAP"). This Array will fill the tile map with the sprite" terrain" when it finds a value equals to "1" and it going to clear the space in the tilemap when it finds a value of "0". Using this simple combination of values also I am going to pro-gramme the algorithms that will generate the terrains in this project.

Page 4: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

ProgrammingThis section has the scripts that allow the game work properly, a lot of the "methods" and variables have their names in "Spanish" Because this game is initially intended for Spanish-Speakers users, but the functions, logic, and content of the script are in English. Also its important to said that each scrip has a brief description about what it

does.

Algorithm Perlin NoiseThis script creates a terrain using the algorithm Perlin noise, which, basically use a random number, called "Seed" to fill the spaces in the Array "MAP", if randomly some space has the value of "1" it will be filled with the sprite Terrain, and if the value is "0" the algorithm will empty this space (no tile). This algorithm creates terrains with sharp edges and very pronuencied "hills" .

public static int[,] Perlinoise(int[,] mapa, float semilla)

{

int Nuevopunto;

//Queremos recibir valores entre -0.5 y 0.5, pero el perlin noise solo nos da valores entre 0 y 1 // Para lograr lo anterior entonces debemos utilizar la variable reducción y restarsela al valor del perlin noise(0 y 1)

float reduccion = 0.5f;

// creamos el perlin noise

for(int x=0; x<=mapa.GetUpperBound(0); x++)

{ Nuevopunto=Mathf.FloorToInt((Mathf.PerlinNoise(x, semilla)-reduccion) *mapa.GetUpperBound(1)) ;

Nuevopunto += (mapa.GetUpperBound(1) / 2);

for (int y = Nuevopunto; y >= 0; y--) { mapa[x, y] = 1;

Page 5: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

}

}

return mapa;

}

public static int [,] softperlinoise(int[,]mapa,float semilla, int intervalo) { if (intervalo > 1) {

//puntos de referencia del proceso de suavizado Vector2Int posicionactual, posicionanterior; //lista de puntos correspondientes para al suavizado según su eje.

List<int> ejexlista = new List<int>(); List<int> ejeylista = new List<int>();

int nuevopunto, puntos;

for (int x = 0; x <= mapa.GetUpperBound(0)+intervalo; x += intervalo) { nuevopunto = Mathf.FloorToInt((Mathf.PerlinNoise(x, semilla)) * mapa.GetUpperBound(1)); ejeylista.Add(nuevopunto); ejexlista.Add(x); } puntos = ejeylista.Count;

for (int i = 1; i < puntos; i++)

{ //posición actual de la x y la y posicionactual = new Vector2Int(ejexlista[i], ejeylista[i]);

//posicion anterior de la x y la y, para tener una referencia y trazar la "linea" de casillas.

posicionanterior = new Vector2Int(ejexlista[i - 1], ejeylista[i - 1]); // diferencia de altura

Vector2 diferencia = posicionactual - posicionanterior; // cuanto a disminuido o aumentado la altura en y

float diferenciaalturay = diferencia.y / intervalo;

float alturactual = posicionanterior.y; // se generan los bloques de casillas desde la x anterior a la x actual. for (int x = posicionanterior.x; x <= posicionactual.x && x < mapa.GetUpperBound(0);x++) {

Page 6: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

for (int y = Mathf.FloorToInt(alturactual); y > 0; y--) { mapa[x, y] = 1; }

alturactual += diferenciaalturay; }

}

} else { mapa = Perlinoise(mapa, semilla); }

return mapa;

Maps Samples:

Page 7: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Algorithm RandomWAlkThis script creates an algorithm that calculates randomly if is necessary to add or re-move tiles "terrain" depending on how high or how low is the terrain around. For example, if the array generates a column filled with sprite "terrain" this algorithm de-termines if is necessary create another next column higher or lower than its neighbor using a random calculation. With this function, I am going to create a series of columns that emulate a terrain with hills and edges(less pronounced than the Perlin Noise).

public static int[,] RandonWalk(int[,] mapa, float semilla) { //convertir la semilla a int del randomwalk

Random.InitState(semilla.GetHashCode());

//escogemos una altura aleatoria dentro del array con las losetas, en el eje y. que es la dimension(1) int ultimaltura = Random.Range(0, mapa.GetUpperBound(1));

//recorremos el mapa en el eje x a lo ancho, por eso ponemos la dimension (0) for (int x = 0; x < mapa.GetUpperBound(0); x++)

{ //0 sube, 1 baja, 2 mantiene la misma altura.

int siguientemovimiento = Random.Range(0, 3);

//sube casillas if (siguientemovimiento == 0 && ultimaltura < mapa.GetUpperBound(1))

{ ultimaltura++; }

//baja casillas else if (siguientemovimiento==1 && ultimaltura>0) { ultimaltura--; }

// si da 2 no hacemos nada, ya que queremos mantener esa altura, según los parametros que dimos

// pintar el mapa en y de losetas:

for (int y = ultimaltura; y > 0; y--)

{

Page 8: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics mapa[x, y] = 1; } }

return mapa; }

Maps Samples:

Page 9: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Algorithm PErlin Noise CAveThis script work using the same principle of Perlin Noise Algorithm, but in this case, I added the borders in the edges of the screen. Likewise, The random number "Seed" that determines the number of spaces filled with the Sprite "Terrains" also will empty spaces in some points inside the "MAP" that will emulate the appearance of a cave.

public static int[,] Perlinoisecave(int[,] mapa, float modificador, bool esborde,float Offsetx=0f, float Offsety=0f,-float semilla=0f )

{ int nuevopunto;

for (int x = 0; x <= mapa.GetUpperBound(0); x++)

{ for (int y = 0; y <= mapa.GetUpperBound(1); y++)

{ if (esborde && (x == 0 || y == 0 || x == mapa.GetUpperBound(0) - 1 || y == mapa.GetUpperBound(1)-1)) { mapa[x, y] = 1; } else

{ nuevopunto = Mathf.RoundToInt(Mathf.PerlinNoise(x * modificador+Offsetx+semilla, y * modifica-dor+Offsety+semilla)); mapa[x, y] = nuevopunto; } }

}

return mapa;

}

Page 10: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Maps Samples:

Page 11: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Algorithm Randomwalk CAveThis script works using the same principle of the RandomWalk algorithm but, in this case, it will leave some empty spaces using two values chosen from a series of values between the maximum and minimum values in the "Y axis" (the heigh of the MAP) and the maximum and minimum value in the "X axis" (the length of the MAP). And also columns filled with "terrain" will be generated both top and down the screen.

public static int[,] Randomwalkcuevas(int[,] mapa, float semilla, float porcentajesueloeliminado)

{ //convertir la semilla a int del randomwalk

Random.InitState(semilla.GetHashCode());

// parametros para crear cuevas int valorminimo = 0; int valormaximoX = mapa.GetUpperBound(0); int valormaximoY = mapa.GetUpperBound(1); int Ancho = mapa.GetUpperBound(0) + 1; int Alto = mapa.GetUpperBound(1) + 1;

// posciones en X, Y en el mapa creado, deben ser aleatorias para que las cuevas se generen diferente cada vez. int posicionX = Random.Range(valorminimo, valormaximoX); int posicionY = Random.Range(valorminimo, valormaximoY);

// calcular cuantas losetas se deben eliminar

int losetashasereliminadas = Mathf.FloorToInt(Ancho * Alto * porcentajesueloeliminado);

int Losetaseliminadas = 0;

while (Losetaseliminadas < losetashasereliminadas)

{ if (mapa[posicionX, posicionY] == 1)

{ mapa[posicionX, posicionY] = 0; Losetaseliminadas++;

}

int direcciónaleatoria = Random.Range(0, 4);

switch (direcciónaleatoria)

Page 12: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

{

case 0:

//arriba posicionY++; break;

case 1:

//Abajo posicionY--; break;

case 2:

//derecha posicionX++; break;

case 3:

//Izquierda posicionX--; break; }

posicionX = Mathf.Clamp(posicionX, valorminimo, valormaximoX);

posicionY = Mathf.Clamp(posicionY, valorminimo, valormaximoY);

}

return mapa;

}

Page 13: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Map Samples

Page 14: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Algorithm moore cellular automataUsing the principles of the "Moore Neighborhood" (This algorithm will check the num-ber of tiles around a central tile and will calculate if is necessary eliminate, add or left the tiles intact in order to create a new terrains). This script will create maps and ter-rains using the Moore Neighborhood and also some basis of the "Game of life" (John Corton Conway).

public static int[,] AutomataCelularMoore(int[,] mapa, int totaldegeneraciones,bool losbordesonmuros) {

for(int i=0; i<totaldegeneraciones; i ++) {

for(int x=0; x <=mapa.GetUpperBound(0); x++)

{

for (int y = 0; y <= mapa.GetUpperBound(1); y++)

{ // Calcular losetas vecinas para ejecutar el algoritmo (incluyendo diagonales) int totalcasillavecinas = cuantascasillasalrededor(mapa, x, y, true);

// Calcularmos si estamos en un borde y ponemos muro if (losbordesonmuros && (x == 0 || x == mapa.GetUpperBound(0) - 1 || y == 0 || y == mapa.GetUpper-Bound(1) - 1)) { mapa[x, y] = 1; }

// si hya más de cuatro casillas al rededor, rellenamos con suelo else if(totalcasillavecinas > 4)

{ mapa[x, y] = 1; }

// si hay menos de 4 casillas alrededor quitamos suelo. else if(totalcasillavecinas<4) { mapa[x, y] = 0; }

} }

}

Page 15: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Map Samples

Page 16: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Algorithm Von Newman cellular automataUsing the principles of the "Newman Neighborhood" (This algorithm will check the number of tiles around a central tile and will calculate if is necessary eliminate, add or left the tiles intact in order to create a new terrains). Is very similar to "Moore Neigh-borhood"

public static int[,] AutomataCelularNueman(int[,] mapa, int totaldegeneraciones, bool losbordesonmuros) {

for (int i = 0; i < totaldegeneraciones; i++) {

for (int x = 0; x <= mapa.GetUpperBound(0); x++)

{

for (int y = 0; y <= mapa.GetUpperBound(1); y++)

{ // Calcular losetas vecinas para ejecutar el algoritmo (incluyendo diagonales) int totalcasillavecinas = cuantascasillasalrededor(mapa, x, y, false);

// Calcularmos si estamos en un borde y ponemos muro if (losbordesonmuros && (x == 0 || x == mapa.GetUpperBound(0) - 1 || y == 0 || y == mapa.GetUpper-Bound(1) - 1)) { mapa[x, y] = 1; }

// si hay más de 2 casillas al rededor, rellenamos con suelo else if (totalcasillavecinas > 2)

{ mapa[x, y] = 1; }

// si hay menos de 2 casillas alrededor quitamos suelo. else if (totalcasillavecinas < 2) { mapa[x, y] = 0; }

} }

}

Page 17: 2D TERRAINS GENERATOR - WordPress.com · 2019. 4. 2. · Using a tile map, and a sprite call ... move tiles "terrain" depending on how high or how low is the terrain around. For ...

Characteristics

Map Samples