Help with while loop and Vector addition

Hi.
So I have a script for my IK spider enemy. In that script I have a function. In that function I get the average position of 6 parts and adding an offset to it. This is my script:

local function doSomething()
    local averagePos = (part1.Position + part2.Position + ... + part6.Position)/6
    --I put the ... so I dont have to write all of the parts' references
   local newPos = averagePos + Vector3.new(0, 10, 0)
   return newPos
end

while wait() do
    torso.Position = doSomething()
end

This just doesn’t work, though. The model flies in the sky because of the while loop being too fast, I think. How could I fix this?

-- Changing 10 to a higher number will make it faster, a lower number will make it slower
local direction = Vector3.new(0, 10, 0)

local function getPosition(delta)
   local averagePos = (part1.Position + part2.Position + ... + part6.Position)/6
    --I put the ... so I dont have to write all of the parts' references
   local newPos = averagePos + (direction * delta) -- calculate offset by direction*delta
   return newPos
end

-- Run code every frame
game:GetService("RunService").Heartbeat:Connect(function(delta)
    -- delta is how much time has passed since you last moved it
    torso.Position = getPosition(delta)
end)
1 Like