I am trying to use SphereCasting as a more efficient way to do hit detection for slow to fast moving projectiles. Previously, I was using GetPartsInPart, but it was too heavy for usage in my game.
When testing, there were inconsistent hit results. The projectiles did not always detect a hit.
^Behavior with SphereCasts
^Intended Behavior with GetPartsInPart
.
Here is the code that CFrames projectiles and SphereCasts.
--manages all active projectiles
game:GetService("RunService").Heartbeat:Connect(function(step: number)
if not Players.LocalPlayer.Character then return end
params.FilterDescendantsInstances = {Players.LocalPlayer.Character.HumanoidRootPart}
local currentTick = tick()
for i = #projectiles,1,-1 do
local projData = projectiles[i]
if not projData then continue end--or projData.Removing then continue end
local part = projData.part
local direction = projData.direction
local speed = projData.speed
local despawnTime = projData.despawnTime
local cache = projData.cache
--despawning checker
if despawnTime>0 and currentTick>=despawnTime then
--print("despawn",part)
projData:Stop(i)
continue
end
--move proj
local increment = step*speed
part.CFrame = part.CFrame+direction*increment
--checks for HumanoidRootPart hits
local sphere = workspace:Spherecast(projData.LastPosition,part.Size.X/2,part.Position-projData.LastPosition,params)
if sphere then
--print("hit",part)
projData:Stop(i)
HitReactionEvent:FireServer(1,"TempSpawner")
local hs = projData.hitSound:Clone()
hs.Parent = Players.LocalPlayer.Character
hs:Destroy()
continue
end
projData.LastPosition = part.Position
end
end)
I am not sure why this is causing problems, but my current guess is the magnitude of the distance parameter in the SphereCast. It might also be limitations with Raycast detection, but I am not very knowledgeable with Raycast.