#unity3d #procedural #topdown
#unity3d #процедурный #сверху вниз
Вопрос:
Я пытаюсь создать 2d-гоночную игру сверху вниз. В этой игре будет случайная дорожная карта каждый раз, когда игрок играет в игру. Я думал о том, чтобы сделать это двумя разными способами: с помощью tilemap или просто сгенерировать дороги, разместив разные префабы (прямые дороги, повороты и т. Д.). Я решил пойти по пути сборных конструкций.
Я считаю, что это должно работать так: иметь сборные квадратные «плитки», по краям которых установлены собственные коллайдеры, чтобы я мог определить, сошел ли игрок с трассы, и в этом случае он взорвался. У меня был бы скрипт MapGenerator, который сгенерирует начальную случайную карту, отслеживая последнюю размещенную плитку (включая ее местоположение и тип дороги: поворот налево, прямо, направо и т.д.). Затем этот скрипт будет продолжать добавлять на дорогу случайным образом по мере приближения игрока к концу, что делает дорогу бесконечной.
Я просто хочу знать, просто ли это неэффективно или я думаю об этом совершенно неправильно.
Вот несколько изображений, показывающих мои дорожные плитки, которые я сделал в photoshop, а затем один сборный образец для прямой дороги (обратите внимание на коллайдеры по ее краям).
Игра, похожая на ту, которую я хочу создать, — это Sling Drift, ссылку на которую я могу предоставить, если хотите. Я не знаю политики добавления ссылок в чат форума.
Кроме того, вот мой код для генератора карт:
//Type of tyle, types are normal (straight road or horizontal road) and turns
public enum MapTileType
{
NORMAL,
N_E,
N_W,
S_E,
S_W
}
//structure for holding the last tile location and its type.
public struct TypedTileLocation
{
public TypedTileLocation(Vector2 pos, MapTileType tyleType)
{
m_tileType = tyleType;
m_position = pos;
}
public Vector2 m_position;
public MapTileType m_tileType;
}
public class MapGenerator : MonoBehaviour
{
//Map Tiles
public GameObject m_roadTile;
public GameObject m_turnNorthWestTile;
//holds all the tiles made in the game
private List<GameObject> m_allTiles;
//Map Tile Widths and Height
private float m_roadTileWidth, m_roadTileHeight;
//Used for generating next tile
TypedTileLocation m_lastTilePlaced;
private void Awake()
{
//store the initial beginning tile location (0,0)
m_lastTilePlaced = new TypedTileLocation(new Vector2(0,0), MapTileType.NORMAL);
//set height and width of tiles
m_roadTileWidth = m_roadTile.GetComponent<Renderer>().bounds.size.x;
m_roadTileHeight = m_roadTile.GetComponent<Renderer>().bounds.size.y;
m_allTiles = new List<GameObject>();
}
// Start is called before the first frame update
void Start()
{
SetupMap();
}
void SetupMap()
{
//starting at the beginning, just put a few tiles in straight before any turns occur
for (int i = 0; i < 6; i)
{
GameObject newTempTile = Instantiate(m_roadTile, new Vector2(0, m_roadTileHeight * i), Quaternion.identity);
m_lastTilePlaced.m_tileType = MapTileType.NORMAL;
m_lastTilePlaced.m_position.x = newTempTile.transform.position.x;
m_lastTilePlaced.m_position.y = newTempTile.transform.position.y;
m_allTiles.Add(newTempTile);
}
//now lets create a starter map of 100 road tiles (including turns and straigt-aways)
for (int i = 0; i < 100; i)
{
//first check if its time to create a turn. Maybe I'll randomly choose to either create a turn or not here
//draw either turn or straight road, if the tile was a turn decide which direction we are now going (N, W, E, S).
//this helps us determine which turns we can take next
//repeat this process.
}
}
void GenerateMoreMap()
{
//this will generate more map onto the already existing road and then will delete some of the others
}
// Update is called once per frame
void Update()
{
}
private void OnDrawGizmos()
{
}
}
Спасибо!
Ответ №1:
Вы пробовали сплайны? Они позволяют легко создавать извилистые дорожки, похожие на гоночные трассы. Если нет, вот видео, которое может помочь: https://www.youtube.com/watch?v=7j_BNf9s0jM .