基于瓦片的随机地图生成像Terraria一样?

时间:2014-10-29 20:15:32

标签: c# random map unity3d procedural

我想使用Unity和C#在游戏Terraria和Starbound等游戏中生成地图 到目前为止,我所做的并不起作用,我不知道为什么......有任何帮助/想法/建议吗?

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);
            }
    }
}
}

1 个答案:

答案 0 :(得分:1)

(heightDiff / dispersionZone)

这是整数除法。请改用(heightDiff / (float)dispersionZone)

* 90

Mathf.Sin以弧度工作,而不是降低。使用* 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);
            }

为什么在创建相同类型的块时使用if?在if和else中,身体之间是否应该存在某种差异?