Help with the new raycasting method to prevent players from using buttons behind walls

Hi! So, I always used Ray.new when scripting anything to do with raycasting, so that’s what I was familiar with. After reading Intro to Raycasting, I decided to give this method a shot.

I’m having difficulty getting the correct intended behavior. I am attempting to make it so when a new ClosestInteractionPart is found, it casts a ray to check if there is any parts between the character and the InteractionPart. The purpose of this is so players can’t use the buttons behind walls.

My Code
function GetClosestInteractionPart()
	local Buttons = GetInteractionParts()
	local ClosestInteractionPart = nil
	local ClosestDistance = math.huge
	for i,v in pairs(Buttons) do
		local Distance = Vars.Player:DistanceFromCharacter(v.Position)
		if Distance <= MaxDistance and Distance < ClosestDistance then
			ClosestInteractionPart = v
			ClosestDistance = Distance
		end
	end
	
	if ClosestInteractionPart then
		local Params = RaycastParams.new()
		Params.FilterDescendantsInstances = {Vars.Player.Character}
		Params.FilterType = Enum.RaycastFilterType.Blacklist
		local RaycastResult = workspace:Raycast(Vars.Player.Character.Head.Position, ClosestInteractionPart.Position, Params)
		EndAttachment.Position = ClosestInteractionPart.Position
		if RaycastResult then
			EndAttachment.Position = RaycastResult.Position
			local Hit = RaycastResult.Instance
			Hit.BrickColor = BrickColor.new('Black')
			ClosestInteractionPart = nil
		end
	end
	
	return ClosestInteractionPart or false
end
In Action

I am honestly clueless to make it work how I intend it to. I would appreciate any assistance.

Check if the player is facing the front or back of the wall, if player is on the opposite side of the wall then we know he is not in the room.

The second argument of Raycast is a direction vector, not a position in space.
Right now, you are doing this:

workspace:Raycast(
    Vars.Player.Character.Head.Position,
    ClosestInteractionPart.Position,
    Params
)

What you probably want to do is something more like this:

local fromPosition = Vars.Player.Character.Head.Position
local toPosition = ClosestInteractionPart.Position
local direction = toPosition - fromPosition
workspace:Raycast(
    fromPosition,
    direction,
    Params
)
1 Like

Thank you! I will try that out.

Edit: Sorry for taking so long to mark as solution. I just had the chance to try it out.