I’m trying to improve the performance of my raycasting code. I cast a ray per render step and apparently it’s causing sight frame drop when this is being called frequently such as shooting a gun with really high fire rate or shotguns, which call this function around 5-10 times at once. This does not happen for weapons with slow fire rate or short range.
https://gyazo.com/d603bd9e5b0e416637c514a43bd5a62c
local stepped
coroutine.wrap(function()
stepped = runservice.RenderStepped:Connect(function(deltaTime)
BulletTrail.Enabled = true
BulletPart.Transparency = 0
local hit,pos,norm = RayCastModule.CastRay(RNG, MouseHitP, deltaTime, OldCF, temptoolStats, BulletPart, char)
OldCF = CFrame.new(pos)
if Firstshot == true then
Firstshot = false
Remotes.SendBulletToClient:FireServer (BulletPart.CFrame, OldCF, BulletPart.Name, temptoolStats.MuzzleVel)
end
BulletPart.CFrame = CFrame.new(pos, pos + (MouseHitP -InitialCF.Position).unit + RNG )
if hit ~= nil or (pos - InitialCF.Position).magnitude >= Range then
stepped:Disconnect()
BulletPart.Transparency = 1
delay(5,function()
debris:AddItem(BulletPart,0)
end)
Remotes.SendBulletToClientImpact:FireServer(BulletPart.Name, hit,pos,norm)
if hit ~= nil then
HandleHit(hit, pos, norm, (pos - InitialCF.Position).magnitude)
end
return
elseif hit == nil then
rayInitialCF = CFrame.new(pos, pos)
end
end)
end)()
And here’s the raycasting module CastRay function:
function RayCastModule.CastRay(RNG, MouseHitP, deltaTime, OldCF, temptoolStats, BulletPart, char)
cs:AddTag(BulletPart, "Ignore1")
cs:AddTag(char,"Ignore1")
local ignored = cs:GetTagged("Ignore1")
local hit,pos,norm = workspace:FindPartOnRayWithIgnoreList(Ray.new(OldCF.Position, RNG * deltaTime * temptoolStats.MuzzleVel),ignored)
return hit,pos,norm
end
Is there anyway to simplify/improve it? I know a lot of games use the similar approach but they have 0 performance problems.