Raycast issues (Simple)

I’m attempting to create a function that measures out 30 studs infront of a face using raycast, and if it’s hit return the distance as a number. Literally the same as the value that would be returned in shooters measuring distance.

I’ve spent 3 hours reading and tinkering, it’s not going well. I cannot find any tutorials or any pages on Dev Wiki.

If you could put how to find such a simple value in the tiniest, most childlike terms for my worm infested brain to understand I’d really appreciate it

here’s my code so far, first time using raycasting.

local function doWeHit()
	local rayOrigin = root.Position
	local rayDestination = (root.CFrame * CFrame.new(0, 0, -30)).p
    local rayDirection = rayDestination - rayOrigin
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {root.Parent}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	if raycastResult then
		local HitSpot = raycastResult.Position
		distToObj = HitSpot - rayOrigin -- I'm aware this does not do what I'd like, it was a last resort.
		return distToObj
	else
		return 30
	end
end
1 Like

Simple answer, going to leave this here incase anyone else needs it.

Reference: Magnitude (roblox.com)
Heres the fixed function too:

local function doWeHit()
	local rayOrigin = root.Position
	local rayDestination = (root.CFrame * CFrame.new(0, 0, -30)).p
    local rayDirection = rayDestination - rayOrigin
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {root.Parent}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	if raycastResult then
		local HitSpot = raycastResult.Position
		local distToObj = (HitSpot - rayOrigin).Magnitude
		return distToObj
	else
		return 30
	end
end
1 Like