The other replies in this thread use while loops to update your cameras position. Do not do this.
I recommend using RunService:BindToRenderStep()
to update your cameras position to be in front of your model.
First you will need to understand what RenderStepped is - RenderStepped fires every frame before rendering (it is also known as PreRender). BindToRenderStep()
is method of RunService that will run a function every RenderStepped, this can later be unbound using UnbindFromRenderStep
.
BindToRenderStep
takes 3 parameters: name, render priority, and the function you want to run. The name parameter is used to unbind and reference your bind, and priority determines when during the render stepped that your function is fired - in your case we will be using Enum.RenderPriority.Camera.Value
(which is 200). The final parameter is self explanatory.
You will need to create your function first, I’ve provided a basic function that will point my camera towards a part.
local target = workspace.Part -- this is the part I want my camera to track.
local camera = workspace.CurrentCamera -- this gets the currently active camera.
local function UpdateCamera()
-- this function is going to be fired every frame, you should never yield if a function is being fired so often. RenderStepped is not a loop, it will not wait for the function to complete before firing again.
local partCF = target.CFrame -- we are going to use the targets CFrame as the base for our camera, then we will apply a CFrame offset so the camera is not inside our target.
local offset = CFrame.new(5, 0, 0) -- this is our offset, this will offset our camera by 5 studs on our targets X axis, you may need to adjust this.
camera.CFrame = partCF * offset -- the * operator is used to add two CFrame values to one another.
-- we have completed our function now.
end
Now that you have your function we can use BindToRenderStep to call it every frame. In the code I’ve provided below the Camera will follow our parts position for 5 seconds before changing back to our character.
camera.CameraType = Enum.CameraType.Scriptable -- our cameras CFrame can only be manipulated outside of the camera script if we have the type to Scriptable.
RunService:BindToRenderStep(‘PartFollow’, Enum.RenderPriority.Camera.Value, UpdateCamera)
task.wait(5)
RunService:UnbindFromRenderStep(‘PartFollow’)
camera.CameraType = Enum.CameraType.Custom -- back to the players normal camera type.
You can take this code and modify it to fit your needs, I have just provided a basic example of how you could accomplish your task. I recommend researching RunService more on the DeveloperHub as well.