I have a self-driving car script, and I made the car follow the road’s orientation at curves. It works well, but the problem is that as it follows the curve, the car slowly drifts away from the original position, sometimes as far as crossing the center line.
The car’s original position is 4.83 studs away from the left edge of the road.
Could someone help me or give some advice on how I could I maintain it’s position?
Here’s the script:
local Debounce = false
function WheelDetection(hit)
if hit.Material == Enum.Material.Concrete and not Debounce then
Debounce = true
if hit.Orientation == Vector3.new(0,0,0) then
else
local Dot = script.Parent.Parent.PrimaryPart.CFrame.RightVector:Dot(hit.CFrame.LookVector)
script.Parent.Parent:SetPrimaryPartCFrame(CFrame.new(script.Parent.Parent.PrimaryPart.CFrame.Position)*CFrame.Angles(0,math.rad(hit.Orientation.Y),0))
if Dot < 0 then
script.Parent.Parent:SetPrimaryPartCFrame(script.Parent.Parent.PrimaryPart.CFrame*CFrame.Angles(0,math.rad(-90),0)) --Left curve
else
script.Parent.Parent:SetPrimaryPartCFrame(script.Parent.Parent.PrimaryPart.CFrame*CFrame.Angles(0,math.rad(90),0)) --Right curve
end
end
wait(0.2)
Debounce = false
end
end
script.Parent.Parent.Wheels.FL.Touched:Connect(WheelDetection)
Best way possible is checking how far you are from the white stripes and the edge of the road to determine how much you need to steer to stay on position.
I suggest making a triangle using three points the part’s position, the edge relative to the part’s position and the lookvector of the parts position. (The part is the car’s primary part)
if you wanted it to drive down the middle with the detection part shouldn’t you just be able to expand the detection part to be a little bigger on each side or would that not work
Basically getting the angle can help you to determine how much to rotate to stay on the same distance like so;
—If it is not a unit vector
function Angle(vectorA, vectorB)
return math.acos(vectorA:Dot(vectorB) / (vectorA.Magnitude * vectorB.Magnitude))
end
— If it is a unit vector
function UnitAngle(vectorA, vectorB)
return math.acos(vectorA:Dot(vectorB))
end
Unit Angle( (edge.Postion-part.Postion).Unit,part.Cframe.Lookvector)
It’s not rotation that is the problem, it’s the position. The rotation part of the script works perfectly as intended, it sets the car to the road’s orientation. What I’d like to know is how I could incorporate the road edge offset into that line? (Line 8)
It’s the A-Chassis script if you don’t know. It has a loop that spins the wheels according to the tune if the _GThrot value is more than 0 (1 in my case).
So based off my order inference the chasis script might move depending on the lookvector of the part because of how the wheels work. Also from looking back on the video it seems as if your car is not rotating on every turn because it might not detect the touch.