Scripting Helpers is winding down operations and is now read-only. More info→
Log in to vote

I'm trying to make a AI car that can Follow a path and stop? First time making a function.

Asked by 9 years ago

Ok so as the title says I'm trying to make an AI Car that can Follow a Path and Stop at certain points in that path, but since I'm still somewhat new to the world of scripting (Should of learn how to script 7 years ago... that's how long I been playing this game...) I don't what to put in my function to make it to follow a brick then stop and follow the path again.

local path = game.ReplicatedStorage.Path
local FollowPath = path.Path
local PathStop = path.PathStop

function FollowPath(path)
    if FollowPath then
        --Don't know what put in here still new to scripting first time scripting a function my self

while true do
    script.Parent.Steer = math.random(0,1)
    script.Parent.Throttle = math.random(0,1)
    script.Parent.MaxSpeed = math.random(15,30)
    script.Parent.Torque = math.random(7,13)
    script.Parent.TurnSpeed = math.random(10,25)

1 answer

Log in to vote
Answered by 9 years ago

I recommend starting with the following algorithm:

-If the car isn't pointed approximately in the direction you want to go, use Steer (a value from -1 to 1) to point it in the right direction. Keep Throttle at 0 during this time. (Consider using the VehicleSeat's CFrame.lookVector and math.atan2 to get the angle the car is travelling as well as the angle you want to be going to, see below)

-Once the car is pointed in the right direction, put Throttle to 1. Keep monitoring the car's angle; follow the previous step's instructions if the angle is no longer acceptable.

-Once you're near the destination, put Throttle to 0 or start travelling to the next destination.

-Optionally, if the car's magnitude to the PathStop brick's position is within a certain value (ex less than 8), put Throttle and Steer to 0.

Using math.atan2:

angleVehicleIsFacing = math.atan2(script.Parent.CFrame.lookVector.Z, script.Parent.CFrame.lookVector.X)) --returns the angle that 'script.Parent' is facing in radians

local dif = target.Position - script.Parent.Position
angleToTarget = math.atan2(dif.Z, dif.X)

--Now you can compare the two angles and take appropriate action. Don't forget that each angle will be between -math.pi and +math.pi, and that if one angle is near math.pi and the other is near -math.pi, the angles are actually quite close.

A more complicated algorithm allows steering and travelling forward/backward at the same time, but then you have to deal with the problem of "overshooting" your target (ex moving forward and turning right at the same time when the target is directly to your right may cause you to move in an orbit around the target).

If you want the car to avoid obstacles on its way to your 'path' brick, you need to get into pathfinding, which is even more complicated.


Answer this question