Need help with raytracing

I’m making a system that allows us to hold objects and I use raytracing to detect walls and prevent object to clip through wall. But when I look at a certain angle to wall, some parts of the object clip through wall. How can I prevent this from happening?

local function mesafe(b)
	local distance = mouse.Hit.Position - character.Head.Position
	part.Position = character.Head.Position + distance.Unit * b
end

local function render()
	local x, y, z = mouse.Hit.X, mouse.Hit.Y, mouse.Hit.Z
	local raycastparams = RaycastParams.new()
	raycastparams.FilterDescendantsInstances = {character, part}
	raycastparams.FilterType = Enum.RaycastFilterType.Exclude
	local raycastresults = workspace:Raycast(character.Head.Position, (mouse.Hit.Position - character.Head.Position) * 300, raycastparams)
	local Magnitude = (character.Head.Position - raycastresults.Position).magnitude
	--print(Magnitude)
	if raycastresults and Magnitude < 10 and Magnitude > 1 then
		b = raycastresults.Distance
		mesafe(b)
	elseif Magnitude > 10 then
		b = 10
		mesafe(b)
	end
end

1 Like

This is due to the fact that your final target of the ray is exactly in the center of the object.

how can ı fix it?

[30char][30char][30char]

I believe it is possible to calculate the distance from the wall and the object. For example, if the object is primitive (for example, a cube). You must move it away from the hit point at a distance equal to half the length of your object (in our case, a cube)