So I’ve been writing an AI car system for a project, and everything was going well until I discovered pathfinding. I’d like the pathfinding waypoints to follow parts called “road”, and stay on their right side. Currently the pathfinding is strange, and for some reason wants to make the car hit a give way sign, despite the destination being in a straight line, in the vehicle’s lane.
I’ve tried putting walls on the edge of the road, and that seemed to fix things a little, but the waypoints are sunken into the road, and I’d like them to be slightly higher (because directly on top or lower would make the car look as if it was sinking in the road). Putting edge walls would also take lots of time and would quickly rack up the part count.
I’m wondering if there’s a better way than just plain edge walls.
Anyways, here’s my code:
local module = {}
wait(5)
local PathfindingService = game:GetService("PathfindingService")
-- Variables for the car and destination, etc.
module.CreatePath = function(par)
local carprimary = par
local destination = game.Workspace.Destinations.South
local path = PathfindingService:CreatePath()
path:ComputeAsync(carprimary.Parent.Body.Position, destination.Position)
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
local part = Instance.new("Part")
part.Shape = "Block"
part.Material = "Neon"
part.Size = Vector3.new(17.95, 4.081, 2)
part.Position = waypoint.Position
part.Anchored = true
part.CanCollide = false
part.Parent = par.Points
end
end
return module
PathfindingService is designed for humanoid locomotion and therefore does not come equipped with this capability by default. What you can do is not follow the waypoints exactly but follow the road that will get you the furthest towards the waypoint. If you recalculate the pathfinding constantly it will probably eventually get you to your destination as long as that destination is on the road.
I say probably because there are still ways to trap the car. You will have to bring out a full A* implementation if you want to do this optimally.
Oh, so I’d need to place waypoints (or their location positions) at junctions, slopes and curves? Then have a script calculate the shortest route and duplicate/insert the waypoints into the car’s “Points” model? Would this be efficient, or is there a better way?