How to allow for camera movement freedom when camera is locked onto a target

What do I want to achieve?

I have a system where I can lock my camera onto enemies:

-- Local script

RS.RenderStepped:Connect(function()
	if CameraLockToggle == true then
		if CameraTarget then -- CameraTarget is chosen in another function
			local lookAtPosition = CameraTarget.HumanoidRootPart.Position
			Camera.CFrame = CFrame.lookAt(Camera.CFrame.Position, lookAtPosition)
		end
	end
end)

The issue is that when the camera is locked, it allows 0 freedom for any additional manual camera movement from the player.

As you can see, whenever I try to move my camera, it snaps back to its original spot. What I’m looking for is how to add some leeway to the camera, while it still faces towards the target.
This would allow for prediction aiming, increased viewing range, and an overall smoother camera experience for the player.

You can lerp the camera’s CFrame to the goal CFrame.

Code:

-- Local script
RS.PreRender:Connect(function(deltaTime)
	if CameraLockToggle == true and CameraTarget then
		local lookAtPosition = CameraTarget.HumanoidRootPart.Position
		Camera.CFrame = Camera.CFrame:Lerp(CFrame.lookAt(Camera.CFrame.Position, lookAtPosition), deltaTime / 10)
	end
end)

The higher the divisor is the higher the time it will take for the camera to snap on.

1 Like

Thank you very much. I had no idea “:Lerp” was a thing.

1 Like

No problem.

By the way, lerp is short for linear interpolation, so for example:

Let’s say I want to lerp the number 5 to the number 10.

This could be done using this:

local num1 = 5
local num2 = 10

num1:Lerp(num2, 0.5)

The 0.5 value is the “alpha” or in other words, the progress. It’s a number from 0 - 1.

In this example, the output would be 7.5, since 7.5 is exactly 50% between 5 and 10.

1 Like

Sorry for asking, but could you send a video of how it looks? I just realized I might want to implement a similar camera in my game, but I’m not sure if it’s what I want yet.

Sure, I got you:

2 Likes

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