Flexible Raycaster

I just made a somewhat decent Raycasting Module on Roblox. That’s it.
Feel free to use or whatever
(Forgot to use Parallel Lua but it’s easy to add)

local RunService: RunService = game:GetService("RunService")
local Raycast = {}

Raycast.__index = Raycast

Raycast.new = function(_Script, _OBJ: Vector3, _OBJDir: string, Distance: number, ParamInfo: RaycastParams, FrameLooping: boolean, IsOnServer: boolean, LoopType: string)
	local self = {
		
		_Script = _Script;
		
		FrameLooping = FrameLooping;
		IsOnServer = IsOnServer;
		LoopType = LoopType;
		
		
		_OBJPos = _OBJ;
		_OBJDir = _OBJDir;
		Distance = Distance;
		ParamInfo = ParamInfo;
	}

	setmetatable(self,Raycast)
	self:Init()
	
	return self
end


function Raycast:ObjectCasted(Params)
	local Direction = nil
	local Object = self._OBJPos.CFrame
	
	if self._OBJDir == "Front" then
		Direction = Object.LookVector
	elseif self._OBJDir == "Back" then
		Direction = -Object.LookVector
	elseif self._OBJDir == "Right" then
		Direction = Object.RightVector
	elseif self._OBJDir == "Left" then
		Direction = -Object.RightVector
	elseif self._OBJDir == "Up" then
		Direction = Object.UpVector
	elseif self._OBJDir == "Down" then
		Direction = -Object.UpVector
	end
	if Direction ~= nil then
		local Result = workspace:Raycast(Object.Position, Direction * self.Distance, Params)
		if Result then
			print("hit")
		end
	end
end


function Raycast:AttributesChanged()
	self._Script:GetAttributeChangedSignal("Direction"):Connect(function()
		print("Changed_Dir")
		self._OBJDir = self._Script:GetAttribute("Direction")
	end)

	self._Script:GetAttributeChangedSignal("Distance"):Connect(function()
		print("Changed_Dist")
		self.Distance = self._Script:GetAttribute("Distance")
	end)
end


function Raycast:Cast()
	local Params = RaycastParams.new()
	Params.FilterDescendantsInstances = {self.ParamInfo}
	Params.FilterType = Enum.RaycastFilterType.Exclude
	
	self:AttributesChanged()
	
	
	warn(self.LoopType)
	warn(self.Distance)
	warn(self._OBJDir)
	
	if self.FrameLooping then
		if self.IsOnServer then
			warn("ServerScript")
			RunService[self.LoopType]:Connect(function()
				self:ObjectCasted(Params)
			end)
		else
			warn("LocalScript")
			RunService[self.LoopType]:Connect(function()
				self:ObjectCasted(Params)
			end)
		end
	else
		self:ObjectCasted(Params)
	end
end


function Raycast:Init()
	self:Cast()
end



return Raycast

quick showcase:

5 Likes