How to make a car traffic?
I want to make a car that follows a road automatically, it detects the streets, puts a path through the whole road. I want like the video shown: https://www.youtube.com/watch?v=Qqapt_AbPv4
This is my code:
local car = workspace.Cars.Car4.Item
local carPrimaryPart = car["primary part"]
local CollectionService = game:GetService("CollectionService")
local PathFindingService = game:GetService("PathfindingService")
local streets = CollectionService:GetTagged("street")
local streetsFinishedDriving = {}
local hasFinishedDriving = false
local function findCurrentStreet()
local raycastOrigin = carPrimaryPart.Position
local raycastDirection = Vector3.new(0, -10000, 0) -- Straight down
local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {streets} -- Ensure streets are grouped
raycastParams.FilterType = Enum.RaycastFilterType.Include
local raycastResult = workspace:Raycast(raycastOrigin, raycastDirection, raycastParams)
if raycastResult then
local street = raycastResult.Instance
if street then
print("Street found:", street)
table.insert(streetsFinishedDriving, street)
return street
else
print("Hit something else:", raycastResult.Instance.Name)
end
else
print("Raycast did not hit anything.")
end
return nil -- Explicitly return nil if no street is found
end
local function findNextStreet(currentStreet)
local closestStreet = nil
local shortestDistance = math.huge
for _, street in streets do
if street ~= currentStreet then
print("current street: ", currentStreet,"street found: ", street)
local distance = (street.Position - currentStreet.Position).Magnitude
local displacement = street.Position - carPrimaryPart.Position
local direction = carPrimaryPart.CFrame.LookVector
print(direction)
local dot = displacement:Dot(direction)
if distance < shortestDistance and dot >= 0.2 then
print("dot: ", dot, "closest street: ", closestStreet, "shortest distance: ", shortestDistance)
for i, finishedDrivingstreet in streetsFinishedDriving do
print(finishedDrivingstreet)
if not (finishedDrivingstreet == street) then
print("Already driving this street")
closestStreet = street
shortestDistance = distance
end
end
end
end
end
return closestStreet
end
local function smoothTurn(carPart, targetPoint)
local currentCFrame = carPart.CFrame
local targetDirection = (targetPoint - carPart.Position).Unit
local targetCFrame = CFrame.lookAt(carPart.Position, carPart.Position + targetDirection)
local deltaRotation = targetCFrame:ToObjectSpace(currentCFrame)
return deltaRotation
end
local function driveTo(startingPos, endingPos)
local path = PathFindingService:CreatePath()
path:ComputeAsync(startingPos, endingPos)
carPrimaryPart:SetNetworkOwner(nil)
local wayPoints = path:GetWaypoints()
local waypoint = 2
local moveToConnection
local linearVelocity = Instance.new("LinearVelocity")
linearVelocity.MaxForce = math.huge
linearVelocity.RelativeTo = Enum.ActuatorRelativeTo.World
linearVelocity.Enabled = true
local angularVelocity = Instance.new("AngularVelocity")
angularVelocity.MaxTorque = math.huge
local attachment = Instance.new("Attachment")
attachment.Parent = carPrimaryPart
linearVelocity.Attachment0 = attachment
linearVelocity.Parent = carPrimaryPart
angularVelocity.Attachment0 = attachment
for i, waypoint in ipairs(wayPoints) do
hasFinishedDriving = false
--if not hasRun or (carPrimaryPart.Position - waypoint.Position).Magnitude < 1 and 2 < #wayPoints then
local direction = (waypoint.Position - carPrimaryPart.Position).Unit
linearVelocity.VectorVelocity = direction * carPrimaryPart.AssemblyMass * 0.06
--angularVelocity.AngularVelocity = smoothTurn(carPrimaryPart, waypoint.Position).LookVector * 15
--end
end
hasFinishedDriving = true
return hasFinishedDriving
end
while true do
local currentStreet = findCurrentStreet()
if currentStreet then
print("Current street detected: ", currentStreet)
local destination = findNextStreet(currentStreet)
if destination then
print("Destination detected: ", destination)
local finishedDriving = driveTo(carPrimaryPart.Position, destination.Position)
if finishedDriving then
driveTo(carPrimaryPart.Position, destination.Position)
end
else
warn("No valid destination found!")
end
else
warn("Failed to detect a current street.")
end
-- Optionally wait before starting again
task.wait(1)
end
Explanation: I detect the current street(raycasting down from the car) and the closest street to the current street, and then just create a path to that closest street, and attach a linear velocity to the car to go to the waypoints of the path to the street.
It can make the car move along the street but most of the time its just back and forth between current and closest street, it also can’t turn, and its extremely unreliable since it keeps creating pathes in real time while driving.
Any help is appreciated!