Preventing FPS Viewmodel clipping by backing it up?

Hello devs! So I am working on my FPS game, and I want to prevent clipping by backing the viewmodel’s CFrame so it goes back, expert devs would say “Use ViewportFrames” well I am using FastCast and when your gun clips it breaks, the problem is this code is very jittery and just doesn’t work right, here’s my code :

runService.Heartbeat:Connect(function()
	if gunViewmodel and originalTip then
		local tip: CFrame = originalTip:ToObjectSpace(gunViewmodel.Weapon.Handle.CFrame) * CFrame.new(0,0,-5) -- The tip of the gun aka where the bullet comes from
		local back: CFrame = tip * CFrame.new(0,0,5)
		local distance = (tip.Position - camera.CFrame.Position).Magnitude / 2
		local result: RaycastResult = workspace:Raycast(back.Position,tip.Position - back.Position,raycastParams)
		if result then
			local dist = (camera.CFrame.Position - result.Position).Magnitude
			backOffset = backOffset:Lerp(CFrame.new(0,0,dist / 2),0.05)
		else
			backOffset = backOffset:Lerp(CFrame.new(),0.05)
		end
	end
end)

Thanks for any help given!

2 Likes

Could you post a video of what is occurring? This would be extremely helpful.

Here :

Found solution. (Character limit brah)

as someone who’s having the same issue, you not stating your solution but instead typing “character limit brah” is very -hindering- helpful to my research

1 Like

It’s literally raycasting and make the current Z axis offset negative distance.

do you have code or could at least tell me how you did that, i know how it works

You have to specify size or length of the gun, then set origin to camera’s position and direction to camera lookVector times size of the gun, then if ray hit something, use ray.Distance to back viewmodel off and if ray didn’t hit anything, reset viewmodel offset. I’m not going to give you any code because you have to learn some stuff yourself and your coding style may not be same as mine.

1 Like

Small question how can he get the size of the gun/viewmodel?

Magnitude or specify it yourself, try some sizes and see what’s right.

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