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.
Driftology/Assets/FenceSpawner.cs

71 lines
2.6 KiB
C#

using UnityEngine;
using System.Collections.Generic;
public class FenceSpawner : MonoBehaviour
{
public Transform waypointsParent; // Parent object holding ordered waypoint transforms
public GameObject fencePrefab; // Prefab of your fence segment
public float segmentSpacing = 1f; // Spacing between repeated segments
public float sideOffset = 2.5f; // Distance from center of the road
void Start()
{
List<Transform> waypoints = new List<Transform>();
foreach (Transform child in waypointsParent)
{
waypoints.Add(child);
}
if (waypoints.Count < 2)
{
Debug.LogError("❌ Not enough waypoints.");
return;
}
Quaternion lastRotation = Quaternion.identity;
for (int i = 0; i < waypoints.Count - 1; i++)
{
Vector3 start = waypoints[i].position;
Vector3 end = waypoints[i + 1].position;
// Smooth forward direction using a look-ahead if possible
Vector3 forward;
if (i < waypoints.Count - 2)
forward = (waypoints[i + 2].position - start).normalized;
else
forward = (end - start).normalized;
Vector3 flatForward = new Vector3(forward.x, 0f, forward.z).normalized;
Vector3 right = Vector3.Cross(Vector3.up, flatForward);
// Compute rotation and smooth it
Quaternion baseRotation = Quaternion.LookRotation(flatForward, Vector3.up);
Quaternion smoothedRotation = (i == 0) ? baseRotation : Quaternion.Slerp(lastRotation, baseRotation, 0.5f);
lastRotation = smoothedRotation;
// Apply prefab orientation correction
//Quaternion finalRotation = smoothedRotation; // if your fence needs X+90
Quaternion finalRotation = smoothedRotation * Quaternion.Euler(90, 0, -90); // if your fence needs X+90
// How many fence segments between this pair
float segmentLength = Vector3.Distance(start, end);
int steps = Mathf.CeilToInt(segmentLength / segmentSpacing);
for (int j = 0; j <= steps; j++)
{
float t = j / (float)steps;
Vector3 center = Vector3.Lerp(start, end, t);
Vector3 leftPos = center - right * sideOffset;
Vector3 rightPos = center + right * sideOffset;
Instantiate(fencePrefab, leftPos, finalRotation, transform);
Instantiate(fencePrefab, rightPos, finalRotation, transform);
}
}
Debug.Log("✅ Fence wall generated from waypoints.");
}
}