Spherecast Wall Collision Issue

Hi.

Could someone tell me why the spherecast is going through the wall and how to prevent it? It appears to not respect the collision once the origin is at the center of the sphere radius.

local RunService = game:GetService('RunService')

local CastVisuals = require(script.CastVisuals)
local SpherecastVisualiser = CastVisuals.new(Color3.new(0, 1, 0))

local function castSphere()
	local origin = workspace.Zombie
	local target = workspace.Target
	
	local raycastResult = SpherecastVisualiser:SphereCast(origin.Position, 4, target.Position-origin.Position)

	if raycastResult then
		warn(raycastResult.Instance)
	end
end

RunService.PreSimulation:Connect(castSphere)
2 Likes

Bump! I posted this late at night.

Roblox SphereCasts Don’t start at the given position the same raycasts do. The given position indicates the position of a sphere with the given radius. Since that imaginary ball is clipping through your wall, it acts the same way a raycast does when it is clipping through a wall and ignores it. If you want the SphereCast to start behind that position and hit anything in front, you should add an offset equal to the radius

Here is a script that adds the offset:

local RS = game:GetService("RunService")

RS.Heartbeat:Connect(function()

	local Start = game.Workspace:FindFirstChild("CastStart")
	local Visual = game.Workspace:FindFirstChild("CastVisual")
	local Goal = game.Workspace:FindFirstChild("CastGoal")

	if not Start or not Visual or not Goal then
		return
	end

	local RCP = RaycastParams.new()
	RCP.FilterDescendantsInstances = {Start,Visual}
	RCP.FilterType = Enum.RaycastFilterType.Exclude

	local CastDirection = Goal.Position-Start.Position
	local CastRadius = Visual.Size.X/2
	local CastOffset = Vector3.new(CastRadius,CastRadius,CastRadius)*CastDirection.Unit
	local CastResult = game.Workspace:Spherecast(Start.Position-CastOffset,CastRadius,CastDirection,RCP)

	if CastResult then
		Visual.Transparency = .5
		Visual.Position = CastResult.Position-CastOffset
	else
		Visual.Transparency = 1
	end

end)

Also, Here is a video which better shows the SphereCast visualization:

And Here is a video which shows what it looks like with the offset:

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.