Happy new year everyone! i hope you are doing well, i got a script here whose viewmodel isn’t really stable, and the gun doesn’t turn in the y-axis with the viewmodel:
local tool = script.Parent
local plr = game.Players.LocalPlayer
local cam = workspace.CurrentCamera
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ViewModelTemplate = ReplicatedStorage:WaitForChild("ViewModel")
local ViewModel
local equipped = false
local function updateViewModelPosition()
if equipped and ViewModel then
local gunHandle = tool:FindFirstChild("Handle")
if not gunHandle then return end
local cameraCFrame = cam.CFrame
local gunCFrame = gunHandle.CFrame
local offset = CFrame.new(0, 0, -1)
local yawRotation = CFrame.Angles(0, cameraCFrame:ToEulerAnglesYXZ(), 0)
local pitchRotation = CFrame.Angles(cameraCFrame:ToEulerAnglesYXZ(), 0, 0)
local viewModelCFrame = gunCFrame * offset * yawRotation * pitchRotation
ViewModel:SetPrimaryPartCFrame(viewModelCFrame)
for _, part in ipairs(ViewModel:GetChildren()) do
if part:IsA("BasePart") then
part.CanCollide = false
end
end
end
end
tool.Equipped:Connect(function()
equipped = true
if not cam:FindFirstChild("ViewModel") then
ViewModel = ViewModelTemplate:Clone()
ViewModel.Parent = cam
end
end)
tool.Unequipped:Connect(function()
equipped = false
if cam:FindFirstChild("ViewModel") then
cam.ViewModel:Destroy()
end
ViewModel = nil
end)
RunService.RenderStepped:Connect(function()
local humanoid = plr.Character and plr.Character:FindFirstChildOfClass("Humanoid")
if not humanoid or humanoid.Health <= 0 then
if cam:FindFirstChild("ViewModel") then
cam.ViewModel:Destroy()
end
return
end
updateViewModelPosition()
end)