Help me with viewmodel

Hi, I have this problem I want the flashlight to stop following the cursor when the camera rotates. As you can see at the beginning everything works and then something breaks does anyone know how to fix it?
video:

script:
local module = {}

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local camera = game.Workspace.CurrentCamera

local cameraModule = require(script.Parent.Camera)

function module.Init()
local viewmodel = script.ViewmodelModel:Clone()
viewmodel.Parent = camera
local x,y,z = nil
game:GetService(“RunService”).RenderStepped:Connect(function()
local camCF = camera.CFrame
local gunPosition = camCF.Position

	local targetPosition = mouse.Hit.Position 
	
	if cameraModule.rotating == true then
		viewmodel:SetPrimaryPartCFrame(camCF * CFrame.Angles(x,y,z))
	else
		viewmodel.PrimaryPart.CFrame = CFrame.lookAt(gunPosition, targetPosition)
		x,y,z = viewmodel.PrimaryPart.CFrame:ToEulerAnglesYXZ()
	end
end)

end

return module

1 Like

The issue is that you’re saving the angles (x, y, z) and reapplying them relative to a moving camera, which makes the viewmodel drift when rotating.

Instead of storing the angles, just store the full CFrame when not rotating and reuse it:

local frozenCFrame

RunService.RenderStepped:Connect(function()
	local camCF = camera.CFrame
	local gunPosition = camCF.Position
	local targetPosition = mouse.Hit.Position

	if cameraModule.rotating then
		if frozenCFrame then
			viewmodel:SetPrimaryPartCFrame(frozenCFrame)
		end
	else
		local newCF = CFrame.lookAt(gunPosition, targetPosition)
		viewmodel:SetPrimaryPartCFrame(newCF)
		frozenCFrame = newCF
	end
end)

Now I have something like this. That’s not what I want, I want the viewmodel to follow the rotation of the camera but also not to move behind the mouse when the camera is in rotation

Makes sense, that’s what causes the weird drift. Then you want to completely ignore the mouse position while rotating and just anchor the viewmodel directly in front of the camera with a fixed offset, no?

Then, when the camera stops rotating, you can go back to making it look at the mouse again if needed.

yes that is exactly what I mean

Then the fix should be simple:

During rotation, just set the viewmodel’s CFrame to camera.CFrame * CFrame.new(0, -1, -2) (or tweak the offset as needed to get the right positioning in front of the camera). This would keep it stable and facing forward regardless of mouse movement.

Once cameraModule.rotating is false again, go back to using CFrame.lookAt() with the mouse target like before.

Let me know if anything else breaks from that, but it should do exactly what you’re after.