You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.3 KiB
C#
71 lines
2.3 KiB
C#
using UnityEngine;
|
|
|
|
public class RoadFenceGenerator : MonoBehaviour
|
|
{
|
|
public GameObject waypointPrefab;
|
|
public float spacing = 2f;
|
|
public LayerMask roadLayer;
|
|
public float raycastHeight = 10f;
|
|
public float raycastDown = 20f;
|
|
public int maxSteps = 1000;
|
|
|
|
private void Start()
|
|
{
|
|
Vector3? start = FindStartPointOnRoad();
|
|
if (!start.HasValue)
|
|
{
|
|
Debug.LogError("❌ No valid road surface found to start waypoint generation.");
|
|
return;
|
|
}
|
|
|
|
Vector3 position = start.Value;
|
|
Vector3 forward = transform.up; // because road is rotated -90 on X, forward is along global Y
|
|
|
|
for (int i = 0; i < maxSteps; i++)
|
|
{
|
|
// Sample centerline at current position
|
|
Vector3 rayOrigin = position + Vector3.up * raycastHeight;
|
|
if (!Physics.Raycast(rayOrigin, Vector3.down, out RaycastHit hit, raycastDown, roadLayer))
|
|
break;
|
|
|
|
Vector3 waypointPosition = hit.point;
|
|
Instantiate(waypointPrefab, waypointPosition, Quaternion.identity, transform);
|
|
|
|
// Sample next point to determine forward direction
|
|
Vector3 nextGuess = waypointPosition + forward * spacing;
|
|
Vector3 nextRay = nextGuess + Vector3.up * raycastHeight;
|
|
|
|
if (!Physics.Raycast(nextRay, Vector3.down, out RaycastHit nextHit, raycastDown, roadLayer))
|
|
break;
|
|
|
|
Vector3 nextPoint = nextHit.point;
|
|
forward = (nextPoint - waypointPosition).normalized;
|
|
|
|
position = waypointPosition + forward * spacing;
|
|
}
|
|
|
|
Debug.Log("✅ Waypoints placed along road center.");
|
|
}
|
|
public Transform startPoint;
|
|
|
|
private Vector3? FindStartPointOnRoad()
|
|
{
|
|
if (startPoint == null)
|
|
{
|
|
Debug.LogError("❌ Please assign a startPoint Transform in the Inspector.");
|
|
return null;
|
|
}
|
|
|
|
Vector3 rayOrigin = startPoint.position + Vector3.up * raycastHeight;
|
|
|
|
if (Physics.Raycast(rayOrigin, Vector3.down, out RaycastHit hit, raycastDown, roadLayer))
|
|
{
|
|
Debug.DrawRay(rayOrigin, Vector3.down * raycastDown, Color.green, 2f);
|
|
return hit.point;
|
|
}
|
|
|
|
Debug.LogError("❌ Raycast from startPoint missed the road.");
|
|
return null;
|
|
}
|
|
}
|