Am building a 2D top down game where there are roads, and intersections, and the user is creating a path, for the car to follow, but that path can be created only on the road, and it has to centre itself on that road. How would I attempt to do this? Am developing in Unity btw.
Right now am gathering the points on input, and based on the direction of the drawn path, it knows if its moving horizontally or vertically, but I am not quite sure how to figure out if its turning. My implementation knows if its turning but it also includes diagonals.
public void InputUpdate()
{
if(Input.GetMouseButtonDown(0))
{
dragPoints.Clear();
lineRenderer.SetVertexCount(0);
horizontalCount = verticalCount = 0;
isDragging = true;
isComplete = false;
}
if(Input.GetMouseButtonUp(0))
{
isDragging = false;
isComplete = true;
}
if(isDragging)
{
Vector3 tempPosition = gameCamera.ScreenToWorldPoint(Input.mousePosition);
tempPosition = new Vector3(tempPosition.x, tempPosition.y, 0f);
if(endPoint == tempPosition || !IsMouseOnRoad(tempPosition))
return;
Vector3 totalDirection = Vector3.zero;
int minSamplePoints = 4;
dragPoints.Add(tempPosition);
startPoint = dragPoints[0];
if(dragPoints.Count > minSamplePoints)
{
endPoint = dragPoints[dragPoints.Count - 1];
for(int i = 0; i + minSamplePoints < dragPoints.Count; i++)
totalDirection += (dragPoints[i + minSamplePoints] - dragPoints[i]).normalized;
prevAvgX = currentAvgX;
prevAvgY = currentAvgY;
currentAvgX = totalDirection.x / dragPoints.Count;
currentAvgY = totalDirection.y / dragPoints.Count;
if(Mathf.Abs(currentAvgY) <= 0.1f)
{
currentAxis = Axis.Horizontal;
horizontalCount++;
}
else if(Mathf.Abs(currentAvgX) <= 0.1f)
{
currentAxis = Axis.Vertical;
verticalCount++;
}
else
{
if(Mathf.Abs(currentAvgX) > Mathf.Abs(currentAvgY))
currentAxis = Axis.TurnXY;
else if (Mathf.Abs(currentAvgX) < Mathf.Abs(currentAvgY))
currentAxis = Axis.TurnYX;
}
}
RenderLine();
}
}
Any help would be much appreciated.
Cheers!!