Path Finding Setup

Through pathfinding, you can designate an exact destination for a vehicle, and it will determine the optimal route to reach it.

By default, pathfinding is disabled due to performance considerations. Computing paths in every frame can be CPU-intensive, so it's advisable to calculate new paths only when necessary.

To enable pathfinding go to Settings Window -> Path Finding and select the Enable Path Finding checkbox.

This action will generate an additional set of waypoints overlaid on the existing ones. These newly created waypoints possess the necessary properties to be utilized for pathfinding using A* algorithms in an optimized manner.

Set Waypoint Penalties

When using pathfinding, certain routes may need to be more appealing than others—for instance, favoring a highway over an adjacent dirt road. By utilizing penalties, you can increase the penalty for traversing the dirt road, prompting algorithms to favor the highway as the optimal route.

To implement penalties, select a waypoint where you intend the penalty to start. Add the penalty value (higher values make the waypoint less favorable for the final path selection). This penalty will be applied to all neighboring waypoints lacking a pre-existing penalty upon pressing Set Penalty. For best practice, proceed to the end of the desired lane where the penalty should cease, reset the penalty to 0, and press Set Penalty again.

Waypoint penalties are visible in the Path Finding window shown in the first image. As you can see there is a red lane with a penalty of 50 and a blue lane with a penalty of 0. In such a scenario, a vehicle is more likely to switch to the blue lane instead of proceeding to the red lane, given its lower penalty value.

After all setup is done press Apply Settings inside the Settings Window.

Path Finding Usage

Instantiate a vehicle with a predefined path

Using the AddVehicleWithPath method, any vehicle can be instantiated at any position along the road waypoints and will drive toward the destination if a valid path exists between the starting and destination points.

The position can be any Vector 3. Upon instantiation, the vehicle will be placed at the closest waypoint to that position. The type of the vehicle needs to be specified so that a vehicle of that type is selected. The destination, also represented as a Vector3 position will result in the selection of the closest waypoint as the designated destination.

Upon reaching the destination, the onDestinationReached event is triggered, providing the vehicle index as a parameter. The developer can then determine the subsequent action for that vehicle, such as stopping and waiting, assigning another destination, or removing the path, allowing the vehicle to continue as a normal traffic vehicle.

If a vehicle has a path it will not be removed from the road by the pooling system only after the path is removed.

Set the destination of an existing vehicle

To direct an already instantiated vehicle to a specific path, the SetDestination method should be used. By providing a vehicle index, you can specify a destination for that vehicle as a Vector3 position. If a viable path exists between the vehicle's current position and the specified destination, the vehicle will initiate movement toward the designated destination. Upon reaching this destination, the onDestinationReached event will be triggered.

Removing a path from a vehicle.

If a vehicle is currently following a designated path but circumstances dictate that the path is no longer necessary, calling the RemoveVehiclePath method with the vehicle index as a parameter will eliminate the path. Subsequently, the vehicle will resume normal behavior as a traffic vehicle.

It's important to note that even after a vehicle reaches its destination, it retains an empty path. To restore its normal behavior, the vehicle's path needs to be removed using the RemoveVehiclePath method.

Implementation Example

In the given example, pressing the spacebar instantiates a new vehicle that will drive from the startPosition to the endPosition. However, the vehicle isn't instantiated immediately after the spacebar is pressed; rather, it occurs only when a vehicle of type Car becomes available. At the time of the button press, all vehicles of type Car might already be on the road.

Upon reaching the destination, the OnDestinationReached event handler (which was added within the Start method) is triggered. In this event handler, a new destination is assigned to that vehicle, directing it toward the position of the DestinationObject.

Finally, the event is removed within the OnDestroy method.

using Gley.TrafficSystem;
using UnityEngine;

public class TestScript : MonoBehaviour
{
    Vector3 startPosition = new Vector3(0, 0, 0);
    Vector3 endPosition = new Vector3(0, 0, 350);

    private void Start()
    {
        Events.onDestinationReached += OnDestinationReached;
    }

    private void OnDestinationReached(int vehicleIndex)
    {
        Debug.Log("Destination Reached" + vehicleIndex);
        if (vehicleIndex != 0)
        {
            API.RemoveVehiclePath(vehicleIndex);
        }
        else
        {
            API.SetDestination(vehicleIndex, GameObject.Find("DestinationObject").transform.position);
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            API.AddVehicleWithPath(startPosition, VehicleTypes.Car, endPosition);
        }
    }

    private void OnDestroy()
    {
        Events.onDestinationReached -= OnDestinationReached;
    }
}

This should give you an overview of how to use Traffic Vehicles with pathfinding.

Get the path between 2 positions

The GetPath method allows you to obtain the list of waypoints required to travel from the start position to the end position for a specific vehicle type. This list can be stored for later use and passed to any vehicle using the SetVehiclePath method.

For detailed instructions about the methods check the Complete APIpage.

Last updated