How to make a function unbinded from a BindToRenderStep() properly

local function OnRenderedFrame(DeltaTime)
				
				Camera.CFrame = PlayerMoverModel.PrimaryPart.CFrame:ToWorldSpace(
								CFrame.Angles(0,math.rad(CurrentRot),0))*CFrame.new(0,0,CurrentDist)
				
				CurrentRot = CurrentRot-ROT_PER_FRAME
				CurrentDist = CurrentDist + (DIST_PER_FRAME)
				
				if CurrentRot == TargetRot and CurrentDist == TargetDist then
					
					RS:UnbindFromRenderStep("checkdelta")
					
				end
				
			end
			
			RS:BindToRenderStep("checkdelta",Enum.RenderPriority.Last.Value,OnRenderedFrame)

In the snippet of code above I want to unbind the function from Render step when both the CurrentRot and CurrentDist reaches the TargetRot and TargetDist ,respectively, however, the animation goes on indefinitely without stopping, how can I correct this error?

You should try using inequalities (> or >=) instead of == when dealing with floating point numbers. The miscalculations from floats can make it very hard for them to eventually equal one number, and instead may equal any different number by the time it reaches (or passes) the target due to computing limitations.

Just change this block:

if CurrentRot == TargetRot and CurrentDist == TargetDist then
					
	RS:UnbindFromRenderStep("checkdelta")
					
end

To this block:

-- changed `==` to `<=` or `>=`
if CurrentRot <= TargetRot and CurrentDist >= TargetDist tehn

	RS:UnbindFromRenderStep("checkdelta")

	-- added this to set the CFrame to the target, might not be needed
	Camera.CFrame = PlayerMoverModel.CFrame:ToWorldSpace(
		CFrame.Angles(0,math.rad(TargetRot),0)) * CFrame.new(0,0,TargetDist)

end
2 Likes

Worked perfectly, thank you very much

1 Like