- Home /
Curving a Path Around an Obstacle
The concept here is that I would like to generate a path from point A to point B. However, both point A and point B are doors that are connected to separate rooms, and I need to ensure that the path connects point A and point B without colliding with any obstacles, much like the image below.
A gentle curve connecting the two paths is preferable
Here is a drawing of what I am looking for.
UPDATE:
I have programmed a method for creating a number of points along a path that successfully avoids obstacles. I still have no method of linking them together in a curve. However, I have been searching the internet for a solution and have stumbled upon spline interpolation, which seems to be exactly what I am looking for. I'm unsure how to implement this in C#. Any help is greatly appreciated.
My code for the points along a path is below.
public void GenPath(Vector3 StartPoint, Vector3 EndPoint)
{
string pathPart = "Prefabs/Environment/Pathways/PathPart";
Vector3[] points = new Vector3[(int)(Vector3.Distance(StartPoint, EndPoint) / 10)]; //number of points in the spline should be based on how far apart the ends of the path are
System.Random r = new System.Random();
for (int i = 0; i < points.Length; i++)
{
StartPoint.y = 0;
EndPoint.y = 0;
points[i] = Vector3.Lerp(StartPoint, EndPoint, ((float)i / points.Length)); //linear interpolation. this places 5 points along a straight line from point A to point B.
points[i].z += (r.Next(0, 101) / 25) - 2; //adjusts each point to give it a more random structure
Collider[] hitColliders = Physics.OverlapSphere(points[i], PathPart.Radius * 2, 1 << 10); //check if the path segment is inside any rooms. Radius is 2* to give space around the path
switch (hitColliders.Length)
{
case 0:
//overlap sphere is already empty, don't have to adjust position further.
break;
default:
Vector3 collidersPos = hitColliders[0].transform.position; //there will only ever be one collider at a time, as the rooms cannot overlap.
while (hitColliders.Length > 0)
{
collidersPos = hitColliders[0].transform.position;
var heading = collidersPos - points[i];
var dist = heading.magnitude;
var dir = heading / dist; //find the directional vector from the point to the center of the room it's touching.
points[i] -= dir; //move the point away from the object it's touching
hitColliders = Physics.OverlapSphere(points[i], PathPart.Radius * 2, 1 << 10); //refresh hitColliders, see if it's empty now.
}
break;
}
Instantiate(Resources.Load(pathPart), points[i], Quaternion.Euler(0, 0, 0)); //after the overlapSphere is empty, instantiate a piece of the path. This will eventually be replaced with a spline interpolation to connect the points.
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer
Mesh generated from bezier curve loop going outside loop 0 Answers