Reputation: 23
I would like to generate a map from tiles like in the games Terraria and Starbound using Unity and C# What I have done so far isn't working and I have no idea why... Any help/ideas/suggestions?
using UnityEngine;
using System.Collections;
public class MapGeneration : MonoBehaviour {
public int mapWidth, mapHeight, spreadDegree;
GameObject[,] blocks;
public GameObject baseBlock;
public int maxHeightAllowed;
public int nullDispersion;
int dispersionZone;
void Start() {
GenerateMap();
}
void GenerateMap() {
dispersionZone = maxHeightAllowed - nullDispersion;
blocks = new GameObject[mapWidth, mapHeight];
for(int x = 0; x < blocks.GetLength(0); x++) {
for(int y = nullDispersion; y <= maxHeightAllowed; y++) {
int heightDiff = y - nullDispersion;
float dispersionModifier = Mathf.Sin( (heightDiff / dispersionZone) * 90);
float random = Random.Range(0, 1);
if(random > dispersionModifier) {
blocks[x,y] = (GameObject)Instantiate(baseBlock, new Vector2(x, y), Quaternion.identity);
} else if (y < blocks.GetLength(1) && blocks[x,y+1] != null) {
blocks[x,y] = (GameObject)Instantiate(baseBlock, new Vector2(x, y), Quaternion.identity);
}
}
for(int y = 0; y < nullDispersion; y++) {
blocks[x,y] = (GameObject)Instantiate(baseBlock, new Vector2(x, y), Quaternion.identity);
}
}
}
}
Upvotes: 0
Views: 2315
Reputation: 12849
(heightDiff / dispersionZone)
This is integer division. Use (heightDiff / (float)dispersionZone)
instead.
* 90
Mathf.Sin
works in radians, not degress. Use * Math.PI/2
if(random > dispersionModifier) {
blocks[x,y] = (GameObject)Instantiate(baseBlock, new Vector2(x, y), Quaternion.identity);
} else if (y < blocks.GetLength(1) && blocks[x,y+1] != null) {
blocks[x,y] = (GameObject)Instantiate(baseBlock, new Vector2(x, y), Quaternion.identity);
}
Why are you using if, when you are creating same type of block? Shouldn't there be some kind of difference between the bodies in if and else?
Upvotes: 1