I want my lerp to have a constant speed even if the screen resolution is small or big.
local speed = 20
local targetPos = UDim2.new(0.5, 0, 0.5, 0)
while true do
local delta = RunService.Heartbeat:Wait()
local origin = guiObject.Position
local direction = (targetPos - origin).Unit
local moveDistance = speed * delta
local newPosition = origin + direction * moveDistance
guiObject.Position = newPosition
end
local RunService = game:GetService(“RunService”)
local guiObject = script.Parent
local speed = 20
local targetPos = UDim2.new(0.5, 0, 0.5, 0)
while true do
local delta = RunService.Heartbeat:Wait()
local originX, originY = guiObject.Position.X.Offset, guiObject.Position.Y.Offset
local targetX, targetY = targetPos.X.Offset, targetPos.Y.Offset
local origin = Vector2.new(originX, originY)
local target = Vector2.new(targetX, targetY)
if (origin - target).Magnitude < speed * delta then
guiObject.Position = targetPos
break
end
local direction = (target - origin).Unit
local moveDistance = speed * delta
local newPosition = origin + direction * moveDistance
guiObject.Position = UDim2.new(
guiObject.Position.X.Scale, newPosition.X,
guiObject.Position.Y.Scale, newPosition.Y
)
end
I don’t see any difference.
My code looks more like this:
local function ConvertScaleToOffset(container, position)
local containerAbsoluteSize = container.AbsoluteSize
return Vector2.new(containerAbsoluteSize.X * position.X.Scale, containerAbsoluteSize.Y * position.Y.Scale)
end
local function ConvertAbsoluteToScale(container, targetOrigin)
local containerAbsolutePos = container.AbsolutePosition
local containerAbsoluteSize = container.AbsoluteSize
local frameRelativePos = targetOrigin - containerAbsolutePos
return UDim2.fromScale(frameRelativePos.X / containerAbsoluteSize.X, frameRelativePos.Y / containerAbsoluteSize.Y)
end
local function GetTargetPosition(guiObject)
local anchorPoint = guiObject.AnchorPoint
local position = guiObject.AbsolutePosition + (guiObject.AbsoluteSize * anchorPoint)
return position
end
local function MoveToTarget(guiObject, targetObject, speed, stopDistance)
local container = guiObject.Parent or guiObject
while true do
local delta = RunService.Heartbeat:Wait()
local origin = GetTargetPosition(guiObject)
local originScale = ConvertAbsoluteToScale(container, origin)
local targetOrigin = GetTargetPosition(targetObject)
local originLevel = Vector2.new(origin.X, targetOrigin.Y)
local distance = (targetOrigin - origin).Magnitude
if distance <= stopDistance then
break
end
local targetPos = originLevel + (targetOrigin - originLevel).Unit * (distance - stopDistance)
local direction = (targetPos - origin).Unit
local moveDistance = speed * delta
local newPosition = origin + direction * moveDistance
local newPositionScale = ConvertAbsoluteToScale(container, newPosition)
guiObject.Position = newPositionScale
end
end