How can I make the block smoothly decelerate into the station

I have a block which acts as a train which is supposed to decelerate from a certain block to another one, and then accelerate to another one after a while of being at the station.

The issue is with the current code, the train just goes at a certain speed and stops instead of decelerating/acceleration smoothly (or at all). Could you help?
The current code:
`local train = game.Workspace.Train1
local startPart = game.Workspace.start_train
local stationPart = game.Workspace.train_station
local stopPart = game.Workspace.train_stop
local speed = 40

local function decelerateTrain(duration)
local initialVelocity = train.AssemblyLinearVelocity

-- Calculate the deceleration force required to stop the train smoothly
local trainMass = train:GetMass()
local decelerationForce = trainMass * initialVelocity.Magnitude / duration

-- Create BodyPosition and BodyVelocity to control the train's motion
local bodyPosition = Instance.new("BodyPosition")
bodyPosition.MaxForce = Vector3.new(decelerationForce, decelerationForce, decelerationForce)
bodyPosition.Parent = train

local bodyVelocity = Instance.new("BodyVelocity")
bodyVelocity.MaxForce = Vector3.new(decelerationForce, decelerationForce, decelerationForce)
bodyVelocity.Velocity = initialVelocity
bodyVelocity.Parent = train

-- Gradually decrease the velocity to stop the train
local startTime = tick()
while tick() - startTime < duration do
	local t = (tick() - startTime) / duration
	bodyVelocity.Velocity = initialVelocity:lerp(Vector3.new(), t)
	wait()
end

-- Stop the train and clean up
bodyPosition:Destroy()
bodyVelocity:Destroy()

end

local function moveTrain(startPosition, endPosition, duration)
local startTime = tick()
while tick() - startTime < duration do
local t = (tick() - startTime) / duration
train.Position = startPosition:Lerp(endPosition, t)
wait()
end
train.Position = endPosition
end

while true do
– Decelerate from start to station
local duration = 8 – You can adjust the duration to make it slower or faster
moveTrain(startPart.Position, stationPart.Position, duration)
decelerateTrain(duration) – Apply gradual deceleration

-- Stop for 40 seconds
wait(40)

-- Accelerate from station to stop
moveTrain(stationPart.Position, stopPart.Position, duration)

-- Stop for 4-5 minutes (random)
wait(math.random(240, 300))

-- Teleport back to start
train.Position = startPart.Position

end `

I suggest instead of using velocity, you should read up on Tween Service

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.