Skip to content

Instantly share code, notes, and snippets.

@coltonoscopy
Last active February 22, 2016 01:07
Show Gist options
  • Save coltonoscopy/d0af2b76fb4f01b1bbe3 to your computer and use it in GitHub Desktop.
Save coltonoscopy/d0af2b76fb4f01b1bbe3 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class MapGenerator : MonoBehaviour {
Sprite[] tileSprites;
int[,] tileMap;
float[,] values;
int width, height;
// Use this for initialization
void Start () {
width = height = 100;
tileSprites = Resources.LoadAll<Sprite>("Sprites/tiles");
tileMap = new int[width, height];
values = new float[width, height];
float shiftX = Random.Range(0, 100);
float shiftY = Random.Range(0, 100);
// noise manipulator values
float a, b, c, d;
a = 0.05f;
b = 1.06f;
c = 1.3f;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
float nx = (float)x / width - 0.5f;
float ny = (float)y / height - 0.5f;
Vector2 pos = new Vector2(nx, ny);
d = 2 * Mathf.Max(Mathf.Abs(pos.x), Mathf.Abs(pos.y));
float e = Mathf.PerlinNoise(nx, ny);
e += 0.5f * Mathf.PerlinNoise(2 * nx, 2 * ny);
e += 0.25f * Mathf.PerlinNoise(4 * nx, 4 * ny);
e = (e + a) * (1 - b * Mathf.Pow(d, c));
print(e);
values[y, x] = e;
}
}
GenerateWater();
GenerateLand();
InstantiateTiles();
}
// Update is called once per frame
void Update () {
}
void InstantiateTiles()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
GameObject go = new GameObject();
SpriteRenderer renderer = go.AddComponent<SpriteRenderer>();
renderer.sprite = tileSprites[tileMap[x, y]];
go.transform.position = new Vector3(x, y, 0);
}
}
}
void GenerateWater()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
tileMap[x, y] = 387;
}
}
}
void GenerateLand()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (values[x, y] < 0.1f)
{
continue;
}
else
{
tileMap[x, y] = 70;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment