How can I loop through this function effectively?

What I’m aiming to do is update the torso once a proximity prompt to face the object, then reset after prompt disappears. Currently, once the player enters proximity zone and triggers function, the waist will update to look at object, however remains in that position even when moving. The return on the function also seems to not work either as the player remains in position after exiting the object’s proximity. I’ve tried applying a while loop but that doesn’t fixes things.

local function update()
	wait(0.1)
	for _,v in pairs(game.Workspace.Items:GetChildren()) do
		if v:FindFirstChild("ProximityPrompt") then
			
			v.ProximityPrompt.PromptShown:Connect(function()
				while true do
					wait(0.1)
					local space = root.CFrame:toObjectSpace(v.CFrame).lookVector.unit
					local space_x = space.X
					local space_y = space.Y
					local asx_torso = math.clamp(-asin(space_x),MIN_TORSO_ROTATE_X,MAX_TORSO_ROTATE_X)
					local asy_torso = math.clamp(asin(space_y),MIN_TORSO_ROTATE_Y,MAX_TORSO_ROTATE_Y)
					waist.C0 = CFrame.new(0,WAIST_Y,0)*CFrame.Angles(0,asx_torso,0)*CFrame.Angles(asy_torso,0,0)
				WaistRotation_Event:FireServer(waist.C0)
				v.ProximityPrompt.PromptHidden:Connect(function()
					return update()
					end)
					end
				end)
1 Like