Better way of raycast for touched?

So I am using a client script to cast a ray so it can detect if something touches the part but it would cause a lot of lag.

local RunService = game:GetService("RunService")

local model = script.Parent
model.Parent:WaitForChild(model.Name)

local Parts = model:WaitForChild("Parts") -- folder

local function onTouched(part, otherPart)
	script.DestroyWeld:FireServer(part)
end

----------------------------------------------------------------------------------------------------------------------------------

local function raycastPart(part)
	local rayOrigin = part.Position
	local rayDirection = ((part.Position).Unit * part.Size.Magnitude) * 2
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection)

	if raycastResult then
		local hit = raycastResult.Instance
		onTouched(part, hit)
	end
end

RunService.Heartbeat:Connect(function()
	for i,v in ipairs(Parts:GetDescendants()) do
		if v:IsA("BasePart") then
			raycastPart(v)
		end
	end
end)
4 Likes

What do you mean by lag? Low performance or…?

Is there a better way of just looping through the folder every hearbeat?

Are you trying to detect if the raycast has hit one of those parts in the folder?

1 Like

Also trying to detect if it has hit any part. I’m trying to create a car crash system.

You can simply raycast every time your mouse moves, and then simply see if that’s the part you’re looking for. You don’t need to go through the list every time.

I don’t think it would be that efficient since the player could not be moving their mouse but still driving.

Maybe every time their mouse intersects something?

But what if the player hovers their mouse over nothing like in the void or the sky?

That value would be “nil”, so we check if that’s not the case.

I guess I will just use the Touched event.

What’s your RayDirection? I thought it was going the part’s facing direction?

It checks around the part to get the part in the break range.

If you want to check around you can use magnitude.

But I would have to check the workspace every heartbeat.

You don’t need to use Heartbeat, but a short enough loop, like task.wait(0.1), or something a bit shorter.

I did also make a crash detection, so I know about this.

I did use a Touched function, and a variable so the script knows it has crashed, and doesn’t need further requests in the function.

I wanted to use raycast because some of the vehicles in my game are sometimes unbreakable and sometimes easy to break:

If that’s the case, you could always just check if there’s a sudden drop in velocity using differences between 2 Vector3s and checking that difference’s Magnitude.

How would I get the other part?