Part doesn't move at constant speed

  1. *What do you want to achieve?
    I want the part to move at a constant speed.

  2. 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)

2 Likes

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)
1 Like

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