Raycast not returning hitResult

:warning: Problem:

  • hitResult’ on line 27 returns as an empty table {},
    it is supposed to include all directions of Rays that hit a block.

  • I’ve included a visualizer of exactly how the Raycast’s shoot
    on the video (See Video Attached), I’ve also made prints to
    confirm that the Ray’s origin and Direction is correct.

  • All blocks in game are Non-Transparent, Touchable & CanCollide-able,
    yet hitResult returns as {}, what to do?

  • Sincerely thanks in advance for any responses! :slight_smile:

:scroll: Code:

local module = {}

local Player = game.Players.LocalPlayer
local Character = Player.Character

local function getSurface(position, object)
    local raycastParams = RaycastParams.new()
    raycastParams.FilterType = Enum.RaycastFilterType.Exclude
    raycastParams.FilterDescendantsInstances = {object}

    local surfaces = {
        Back = Vector3.new(0, 0, -1);
        Front = Vector3.new(0, 0, 1);
        Top = Vector3.new(0, 1, 0);
        Bottom = Vector3.new(0, -1, 0);
        Right = Vector3.new(1, 0, 0);
        Left = Vector3.new(-1, 0, 0);
	}
	
	local touchedSurfaces = {}
	for side, normal in pairs(surfaces) do
		
        local rayOrigin = position + normal * (object.Size / 2)
        local rayDirection = normal * (object.Size.Magnitude / 2)
		local hitResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
		
        if hitResult then
            if hitResult.Instance == object then
                table.insert(touchedSurfaces, side)
            end
        end
    end
    return touchedSurfaces
end

local function removeSurfaceTexture(Block, Position)
	spawn(function()
		local Surface = getSurface(Block.Position, Block)
		
		if Surface then
			print(Surface)
			for Num, Surfaces in ipairs(Surface) do
				print(Block[Surfaces[Num]])
				Block[Surfaces[Num]].Enabled = false
			end
		else
			for _, Guis in ipairs(Block:GetChildren()) do
				if Guis:IsA("SurfaceGui") then
					Guis.Enabled = true
				end
			end
		end
	end)
end

game.Workspace.Blocks.ChildAdded:Connect(function(Block)
	if Block:IsA("Part") and Block.Name == "Glass" then
		removeSurfaceTexture(Block, Block.Position)
	end
end)

game.Workspace.Blocks.ChildRemoved:Connect(function(Block)
	if Block:IsA("Part") and Block.Name == "Glass" then
		removeSurfaceTexture(Block, Block.Position)
	end
end)

return module

1 Like

Raycasts don’t use CanCollide, they use CanQuery. Is CanQuery on for the parts?

This could also be the problem:

It may be that the rays are being cast slightly inside of the part you would expect them to collide with. Since ray’s don’t hit interior faces, you might try changing the surfaces table to this:

local surfaces = {
    Back = Vector3.new(0, 0, -0.9);
    Front = Vector3.new(0, 0, 0.9);
    Top = Vector3.new(0, 0.9, 0);
    Bottom = Vector3.new(0, -0.9 0);
    Right = Vector3.new(0.9, 0, 0);
    Left = Vector3.new(-0.9, 0, 0);
}
1 Like