[TUTORIAL] Preventing Viewmodel Clipping From Wall by Moving the Viewmodel Back

How does this work?

This works by raycasting relative to the camera and not the guns tip.

First Step. We make a new raycast and fire it.

self.raycastParams = RaycastParams.new();
self.raycastParams.FilterType = Enum.RaycastFilterType.Exclude;
self.raycastParams.FilterDescendantsInstances = {self.character, self.viewmodel};
self.raycastParams.IgnoreWater = true;

self.viewmodelClippingRaycastResult = workspaceService:Raycast(self.currentCamera.CFrame.Position + self.currentCamera.CFrame.LookVector * -5, self.currentCamera.CFrame.LookVector * 8, self.raycastParams);

--[[
 8 is your raycast length. We multiply the origin by -5 to make sure the raycast fires behind the original position of the camera
--]]

Final Step. We check if the raycast hit anything and adjust accordingly to the raycast distance. We Subtract the raycast distance from 8 to reverse the offset. (Viewmodel moves farther when closer);

if self.viewmodelClippingRaycastResult then
		self.viewmodelClippingOffsetCFrame = self.viewmodelClippingOffsetCFrame:Lerp(CFrame.new(0, 0, 8 - self.viewmodelClippingRaycastResult.Distance), 12 * deltaTime);
	else 
		self.viewmodelClippingOffsetCFrame = self.viewmodelClippingOffsetCFrame:Lerp(CFrame.new(0,0,0), 9 * deltaTime);
	end

Heres a video and what the full function looks like

function viewmodelController:SetViewmodelClippingOffset(deltaTime: number)
	self.viewmodelClippingRaycastResult = workspaceService:Raycast(self.currentCamera.CFrame.Position + self.currentCamera.CFrame.LookVector * -5, self.currentCamera.CFrame.LookVector * 8, self.raycastParams);

	if self.viewmodelClippingRaycastResult then
		self.viewmodelClippingOffsetCFrame = self.viewmodelClippingOffsetCFrame:Lerp(CFrame.new(0, 0, 8 - self.viewmodelClippingRaycastResult.Distance), 12 * deltaTime);
	else 
		self.viewmodelClippingOffsetCFrame = self.viewmodelClippingOffsetCFrame:Lerp(CFrame.new(0,0,0), 9 * deltaTime);
	end
end

6 Likes

Really good idea, but I’d say update it. Instead of just making move back like in dead rails, make the size smaller and move it closer to the camera so it doesn’t look weird.

1 Like