Any alternative to spherecast?

Hey, I recently tried to recreate my own sphere/boxcast. This didn’t work, so I want to know how to create an alternative that works in Roblox. Is there any module or script I could use to do this?

Here is the code if you want:

Failed test :(
local module = {}

function module.BoxCast(BoxSize,Origin,Direction,Steps)
	local Box = Instance.new("Part")
	if typeof(BoxSize) == Vector3 then
		Box.Size = BoxSize
	else
		Box.Size = Vector3.new(BoxSize,BoxSize,BoxSize)
	end
	Box.Parent = workspace
	
	Box.CFrame = CFrame.new(Origin,Origin+Direction)
	for i = 0,1,1/(Steps+(Origin-Direction).Magnitude) do
		Box.Position:Lerp(Origin+Direction,i)
		local TouchingParts = Box:GetTouchingParts() --Gets intersecting parts
		if #TouchingParts > 0 then 
			Box:Destroy()
			return TouchingParts,Box.Position
		else
			Box:Destroy()
			return nil
		end --Prevents printing an empty table
	end
end

return module

What did you expect to happen with this code, and what happened instead?

I expected a box to be made and lerp to the direction like a normal raycast. The steps is how many times it will check while moving to the direction. And since the box is anchored, nothing happens.

Can you print what’s happening?

No not really. Since anchored parts can’t detect collisions, it’s always nil.

Really? Is your anchored object always CanCollide=false and CanTouch=false?

You can check the code you know. The box in this script isn’t anchored. But since the script runs in under a frame I don’t think the physics work.

Save Box.Position before destroying.

? I am saving it. In a different script I recieve Box.Position after returning.

You might want to look into Roblox’s new spatial query API here. It has functions which can get parts within a box as well as within a sphere.

Finally we can nicely do this:

Introducing Shapecasts - Updates / Announcements - DevForum | Roblox :slight_smile:

1 Like

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