Best way of detecting when a part has hit the front surface of another part

Hello! I am trying to build a Level Crossing for a Railway Game. In order for the barriers to lower, a train with multiple parts acting as sensors must touch the front side of a part that acts like a trigger sensor.

For now, I tried the code in the codeblock. In Roblox Studio, it worked. But in a live server, it detected front, back, and bottom.

Any help is appreciated!

local TriggerSensor = script.Parent

function getSurface(position, object)
	local surfaces = {
		back = object.CFrame * CFrame.new(0, 0, object.Size.Z);
		front = object.CFrame * CFrame.new(0, 0, -object.Size.Z);
		top = object.CFrame * CFrame.new(0, object.Size.Y, 0);
		bottom = object.CFrame * CFrame.new(0, -object.Size.Y, 0);
		right = object.CFrame * CFrame.new(object.Size.X, 0, 0);
		left = object.CFrame * CFrame.new(-object.Size.X, 0, 0);
	}
	local surface = "back"
	for side, cframe in pairs (surfaces) do
		surface = ((position - cframe.p).magnitude > (position - surfaces[surface].p).magnitude and surface or side)
	end
	return surface
end

TriggerSensor.Touched:Connect(function(hit)
	if hit.Name == "Sensor" then
		if getSurface(hit.Position, TriggerSensor) == 'front' then
			--Lower barrier, blah blah blah
		end
	end
end)