*What do you want to achieve?
I want the part to move at a constant speed.
What is the issue?
It doesn’t move at a constant speed.
local RunService = game:GetService("RunService")
local speed = 20
local moveObject = workspace.movePart
local startPosition = workspace.moveStart.Position
local targetPosition = workspace.moveEnd.Position
local distance = (moveObject.Position - targetPosition).Magnitude
local moveTime = (distance / speed)
local runningTime = 0
local connection
connection = RunService.Heartbeat:Connect(function(DeltaTime)
runningTime += DeltaTime
local alpha = runningTime / moveTime
print(alpha)
moveObject.Position = moveObject.Position:Lerp(targetPosition, alpha)
if alpha >= 1 then
print("disconnected")
connection:Disconnect()
end
end)
I just threw the code into ChatGPT and it found the mistake. Here is the updated code:
local RunService = game:GetService("RunService")
local speed = 20
local moveObject = workspace.movePart
local startPosition = workspace.moveStart.Position
local targetPosition = workspace.moveEnd.Position
local direction = (targetPosition - startPosition).Unit -- Normalized direction vector
local distance = (startPosition - targetPosition).Magnitude
local moveTime = distance / speed
local runningTime = 0
local connection
connection = RunService.Heartbeat:Connect(function(DeltaTime)
runningTime += DeltaTime
local travelDistance = speed * runningTime -- Total distance traveled so far
local newPosition = startPosition + direction * travelDistance
if travelDistance >= distance then
newPosition = targetPosition
print("disconnected")
connection:Disconnect()
end
moveObject.Position = newPosition
end)