Raycasting from a vector3 to other is not working as I expect

Hi!
I got this code;

Relicated.Events.Hit.OnClientEvent:Connect(function(lookAt)
	if (Player:DistanceFromCharacter(lookAt) <= 10) then
		local char =Player.Character
		if (char) then
			local root = Player.Character:WaitForChild("HumanoidRootPart")
			local rayParams = RaycastParams.new()
			rayParams.FilterDescendantsInstances = {workspace.GunEngine,char}
			rayParams.FilterType = Enum.RaycastFilterType.Blacklist
			local rayCast = workspace:Raycast(root.Position,(root.Position - lookAt).Unit * 10)
			if (rayCast) then
				
				if (rayCast.Position == lookAt) then
					
				end
			end
		end
	end;
end)

I am raycasting to make it go straight from the Head of the Player, to the point which is closer than 10 studs, the thing is it’s not working, it might be this
local rayCast = workspace:Raycast(root.Position,(root.Position - lookAt).Unit * 10)
root.Position is the head position, start, lookAt is where the ray should go to

Your direction is backwards. Swap the subtraction expression.

I made that, still is the same

Other than the direction (the (root.Position - lookAt)) being backwards, the only thing I see wrong with it is this:

if (rayCast.Position == lookAt) then

This will never, ever be true.
If you want to check whether two Vector3s are at the same position, then you have to check whether they’re really, really close to each other.

if (rayCast) then
	-- you should've put a print right here anyway if this part "didn't work"
	print("Raycast hit something")
	
	if (rayCast.Position:FuzzyEq(lookAt, 0.2)) then -- the 0.2 can be removed, the default is a super tiny value
		print("Hit position is within 0.2 studs of aimed location")
	else
		print("Something is in the way")
	end
else
	print("Raycast hit the air") -- and here
end

1 Like

What does FuzzyEq does?
Some kind of magnitude?

It’s pretty much this:

function Vector3.FuzzyEq(A, B, magnitude)
	return (B - A).Magnitude < (magnitude or 1e-5)
end

Look for FuzzyEq

1 Like