ryzerrr's picture
Upload folder using huggingface_hub
6cae93f verified
Raw
History Blame Contribute Delete
2.7 kB
using System.Collections.Generic;
using UnityEngine;
namespace UnityAgent
{
/// <summary>
/// Lays out a grid road network at runtime: builds thin box meshes for
/// roads and an intersection marker at every grid crossing.
/// </summary>
public class RoadNetwork : MonoBehaviour
{
[Header("Grid")]
public int gridSize = 5;
public float blockSpacing = 30f;
public float roadWidth = 6f;
public float roadThickness = 0.1f;
[Header("Materials")]
public Material roadMaterial;
public Material intersectionMaterial;
private readonly List<GameObject> _roads = new List<GameObject>();
private void Start()
{
Build();
}
public void Build()
{
foreach (var r in _roads) if (r != null) Destroy(r);
_roads.Clear();
float total = (gridSize - 1) * blockSpacing;
Vector3 origin = transform.position - new Vector3(total * 0.5f, 0f, total * 0.5f);
for (int i = 0; i < gridSize; i++)
{
// Horizontal road
_roads.Add(SpawnRoad(
new Vector3(origin.x + total * 0.5f, 0f, origin.z + i * blockSpacing),
new Vector3(total + roadWidth, roadThickness, roadWidth),
roadMaterial, $"Road_H_{i}"));
// Vertical road
_roads.Add(SpawnRoad(
new Vector3(origin.x + i * blockSpacing, 0f, origin.z + total * 0.5f),
new Vector3(roadWidth, roadThickness, total + roadWidth),
roadMaterial, $"Road_V_{i}"));
}
// Intersections.
for (int x = 0; x < gridSize; x++)
{
for (int z = 0; z < gridSize; z++)
{
Vector3 p = new Vector3(origin.x + x * blockSpacing, 0f, origin.z + z * blockSpacing);
_roads.Add(SpawnRoad(p, new Vector3(roadWidth * 1.2f, roadThickness * 1.5f, roadWidth * 1.2f),
intersectionMaterial, $"Intersection_{x}_{z}"));
}
}
}
private GameObject SpawnRoad(Vector3 pos, Vector3 scale, Material mat, string name)
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.name = name;
go.transform.SetParent(transform, false);
go.transform.position = pos + transform.position;
go.transform.localScale = scale;
if (mat != null) go.GetComponent<MeshRenderer>().sharedMaterial = mat;
return go;
}
}
}