Checking if wall is in the way between player and seat

Hello. I scripted a basic “press E to sit” system for use in my bus game. It works great except for one issue. You can still sit in the passenger seats through walls. See the video I attached bellow.
robloxapp-20201118-1522295.wmv (2.5 MB)
And if you are wondering about how it works. All the seats are tagged using the tag editor plugin. Tagged under the tag “Seats” and they is a single local script that runs in StarterCharacterScripts.
Here is the code for the seat controller script that all characters spawn with and controls the system.

Code

local SEATS_TAG = “Seats”
local SIT_DISTANCE = 5

local cs = game:GetService(“CollectionService”)
local cas = game:GetService(“ContextActionService”)

local player = game.Players.LocalPlayer
local humanoid = script.Parent:WaitForChild(“Humanoid”)

local seats = cs:GetTagged(SEATS_TAG)

local closestSeat = nil

function SitRequest(name, state, input)
if (state == Enum.UserInputState.Begin) then
if (closestSeat) then
if (humanoid.Sit) then
humanoid.Jump = true
else
closestSeat:Sit(humanoid)
end
end
end
end

cs:GetInstanceAddedSignal(SEATS_TAG):Connect(function(seat)
table.insert(seats, seat)
end)

cs:GetInstanceRemovedSignal(SEATS_TAG):Connect(function(seat)
seats = cs:GetTagged(SEATS_TAG)
end)

cas:BindAction(“SitRequest”, SitRequest, false, Enum.KeyCode.E, Enum.KeyCode.ButtonX)

while (true) do
local seat = nil
local minDist = math.huge
for _,s in pairs(seats) do
local distance = player:DistanceFromCharacter(s.Position)
if (distance < SIT_DISTANCE and distance < minDist) then
seat = s
minDist = distance
end
end
closestSeat = seat
player.PlayerGui.Gui.SitMessage.Visible = (seat ~= nil and not humanoid.Sit and not seat.Occupant)
wait(0.1)
end

I read somewhere else about doing a raycast but idk how to implement it into this script.

Raycasting was the first thing that came to my mind whilst reading your situation. I would recommend you do some research on raycasting in the Roblox Developer Hub, as well as posts in the Dev Forum.

Good luck!

fixed your codeblock, but using a raycast in your situation is a great way to find out if a block is in the way. you can raycast in a certain direction and it will return a result (i think). then you can use the result to find the magnitude (distance between two parts) to determine if a wall was in the way.

How about you just make the distance to be the seat even lower than 5 studs?

say like 3