Привет придумай сложный скрипт связанный с генерацией на юнити 3д
- User
Привет придумай сложный скрипт связанный с генерацией на юнити 3д
- Assistant
- User
а можешь еще придумать скрипты
- Assistant
Привет придумай сложный скрипт связанный с генерацией на юнити 3д
а можешь еще придумать скрипты
Конечно, давай создадим сложный скрипт на языке C#, который генерирует случайно распределённые скалы на процедурно создаваемом острове в Unity. Мы будем использовать Perlin Noise для генерации карты высот и размещения объектов.
Шаги:
Для этого создадим скрипт IslandGenerator.cs:
using UnityEngine;
public class IslandGenerator : MonoBehaviour
{
public int width = 256;
public int height = 256;
public float scale = 20f;
public float heightMultiplier = 10f;
public AnimationCurve heightCurve;
public GameObject rockPrefab;
public float rockSpawnProbability = 0.01f; // вероятность появления скалы
// Основной метод генерации
void Start()
{
GenerateIsland();
}
void GenerateIsland()
{
// Генерация карты высот с использованием Perlin Noise
float[,] heightMap = GenerateHeightMap();
// Создание меша и его наложение
Mesh mesh = GenerateMesh(heightMap);
GetComponent<MeshFilter>().mesh = mesh;
// Размещение скал
PlaceRocks(heightMap);
}
float[,] GenerateHeightMap()
{
float[,] heightMap = new float[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
float xCoord = (float)x / width * scale;
float yCoord = (float)y / height * scale;
float perlinValue = Mathf.PerlinNoise(xCoord, yCoord);
heightMap[x, y] = heightCurve.Evaluate(perlinValue) * heightMultiplier;
}
}
return heightMap;
}
Mesh GenerateMesh(float[,] heightMap)
{
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[width * height];
int[] triangles = new int[(width - 1) * (height - 1) * 6];
int vertIndex = 0;
int triIndex = 0;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
vertices[vertIndex] = new Vector3(x, heightMap[x, y], y);
if (x < width - 1 && y < height - 1)
{
triangles[triIndex + 0] = vertIndex;
triangles[triIndex + 1] = vertIndex + width + 1;
triangles[triIndex + 2] = vertIndex + width;
triangles[triIndex + 3] = vertIndex;
triangles[triIndex + 4] = vertIndex + 1;
triangles[triIndex + 5] = vertIndex + width + 1;
triIndex += 6;
}
vertIndex++;
}
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
return mesh;
}
void PlaceRocks(float[,] heightMap)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (Random.value < rockSpawnProbability)
{
float height = heightMap[x, y];
Vector3 position = new Vector3(x, height, y);
Instantiate(rockPrefab, position, Quaternion.identity);
}
}
}
}
}
MeshFilter, MeshRenderer и скрипт IslandGenerator.rockPrefab вашего скрипта.Эта генерация включает в себя процедурное создание острова на основе шума Перлина и размещение скал с определённой вероятностью. Подбор параметров heightCurve, width, height, scale и heightMultiplier позволит вам добиться разнообразных и уникальных результатов рельефа.
Конечно, вот ещё два более сложных скрипта для Unity, которые также можно использовать в проекте на процедурной генерации. Один скрипт будет ответственен за создание реки, а другой — за создание деревьев на вашем острове.
Создадим скрипт RiverGenerator.cs, который проложит извилистую реку через вашу карту.
using System.Collections.Generic;
using UnityEngine;
public class RiverGenerator : MonoBehaviour
{
public int width = 256;
public int height = 256;
public int riverWidth = 4;
public Material riverMaterial;
// Основной метод генерации
void Start()
{
GenerateRiver();
}
void GenerateRiver()
{
List<Vector3> riverPath = FindRiverPath();
foreach (Vector3 position in riverPath)
{
CreateRiverSegment(position);
}
}
List<Vector3> FindRiverPath()
{
List<Vector3> path = new List<Vector3>();
int currentX = Random.Range(0, width);
int currentY = 0;
while (currentY < height)
{
path.Add(new Vector3(currentX, 0, currentY));
currentY++;
if (Random.value > 0.5f)
{
currentX += Random.value > 0.5f ? 1 : -1;
currentX = Mathf.Clamp(currentX, 0, width - 1);
}
}
return path;
}
void CreateRiverSegment(Vector3 position)
{
for (int dx = -riverWidth / 2; dx <= riverWidth / 2; dx++)
{
for (int dy = -riverWidth / 2; dy <= riverWidth / 2; dy++)
{
Vector3 segmentPosition = new Vector3(position.x + dx, position.y, position.z + dy);
GameObject riverSegment = GameObject.CreatePrimitive(PrimitiveType.Quad);
riverSegment.transform.position = segmentPosition + Vector3.up * 0.01f; // чуть-чуть выше поверхности
riverSegment.transform.rotation = Quaternion.Euler(90, 0, 0); // горизонтально
riverSegment.transform.localScale = new Vector3(1, 1, 1);
riverSegment.GetComponent<Renderer>().material = riverMaterial;
}
}
}
}
RiverGenerator.riverMaterial.Создадим скрипт TreeGenerator.cs, который будет отвечать за размещение деревьев на вашем острове.
using UnityEngine;
public class TreeGenerator : MonoBehaviour
{
public int width = 256;
public int height = 256;
public GameObject treePrefab;
public float treeDensity = 0.02f; // плотность деревьев
// Основной метод генерации
void Start()
{
GenerateTrees();
}
void GenerateTrees()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (Random.value < treeDensity)
{
Vector3 position = new Vector3(x, 0, y);
PlaceTree(position);
}
}
}
}
void PlaceTree(Vector3 position)
{
float terrainHeight = GetTerrainHeight(position);
position.y = terrainHeight;
Instantiate(treePrefab, position, Quaternion.identity);
}
float GetTerrainHeight(Vector3 position)
{
// Возвращаем высоту на основе позиции
// Для простоты, можно использовать Raycasting из воздуха вниз
position.y = 100;
Ray ray = new Ray(position, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
return hit.point.y;
}
return 0; // если не найдено, возвращаем 0
}
}
TreeGenerator.treePrefab.treeDensity и размеры острова для получения желаемого результата.Эти два скрипта помогут создать процедурно генерируемый остров с рекой и деревьями, что добавит реалистичности и разнообразия вашему игровому миру.
Not yet included in a published release.