Use that function with a part in the face of the car that would be making contact with something (e.g the front of the car if the Z axis suddenly dropped).
Alternatively you could calculate the part in the negative direction of the deceleration (for example, if the difference between the last and current velocity pointed to the back of the car, the part that would most likely be hit would be in the front of the car)
If there’s no results (where the parts are not attached to the car), then assume the car did not crash.
This might seem a little “exotic”, but it could work.
What I would do is save the last position and check the distance. Then use a Touched function, then you can check that previous distance to see how intense the crash was.
local lastVelocity = Vector3.new(0, 0, 0)
RunService.Heartbeat:Connect(function()
for i,v in ipairs(Parts:GetDescendants()) do
if v:IsA("BasePart") then
local currentVelocity = v.AssemblyLinearVelocity
local velocityChange = (currentVelocity - lastVelocity).Magnitude
v.Touched:Connect(function(hit)
breakPart(v, hit)
end)
lastVelocity = currentVelocity
end
end
end)
local function raycastPart(part)
local rayOrigin = part.Position
local rayDirection = ((part.Position).Unit * part.Size.Magnitude) * 2
local raycastResult = workspace:Spherecast(part.Position, part.Size.Magnitude, rayDirection)
if raycastResult then
local hit = raycastResult.Instance
local speed = (part.AssemblyLinearVelocity - hit.AssemblyLinearVelocity).Magnitude
if speed >= 60 then
onTouched(part, hit)
end
end
end
game:GetService("RunService").Heartbeat:Connect(function()
for i,v in ipairs(Parts:GetDescendants()) do
if v:IsA("BasePart") then
raycastPart(v)
end
end
end)
No need to do any ray traces before, just look and see if the velocity has gone down fast, if so, then do the ray. You can also do a touched event on the body of the car rather then check if the velocity has gone down.
local lastVelocity = {}
for i,v in ipairs(Parts:GetDescendants()) do
if v:IsA("BasePart") then
v:GetPropertyChangedSignal("AssemblyLinearVelocity"):Connect(function()
local currentVelocity = v.AssemblyLinearVelocity
local velocityChange = (currentVelocity - lastVelocity[v]).Magnitude
lastVelocity[v] = currentVelocity
end)
v.Touched:Connect(function(hit)
breakPart(v, hit)
end)
end
end