Hey, I’m trying to track the speed of anchored parts moved by non-physics based means such as tweens etc. In other words, I’m trying to replicate having AssemblyLinearVelocity but for anchored parts. Here’s my code:
local SPEED_THRESHOLD = 50
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local lastPositions = {}
local lastUpdateTimes = {}
local function updateAnchoredVelocities()
local currentTime = tick()
for _, obj in ipairs(workspace:GetDescendants()) do
if obj:IsA("BasePart") and obj.Anchored then
local lastPos = lastPositions[obj] or obj.Position
local lastTime = lastUpdateTimes[obj] or currentTime
local deltaTime = currentTime - lastTime
if deltaTime > 0 then
local velocity = (obj.Position - lastPos).Magnitude / deltaTime
obj:SetAttribute("CustomVelocity", velocity)
end
lastPositions[obj] = obj.Position
lastUpdateTimes[obj] = currentTime
end
end
end
RunService.PreSimulation:Connect(updateAnchoredVelocities)
local function onCharacterAdded(character)
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
if not humanoidRootPart then return end
local function onPartTouched(hit)
if hit and hit:IsA("BasePart") then
local velocity = hit.AssemblyLinearVelocity.Magnitude
local customVelocity = hit:GetAttribute("CustomVelocity") or 0
if math.max(velocity, customVelocity) > SPEED_THRESHOLD then
print(character.Name .. " was hit by a fast-moving object: " .. hit.Name ..
" (Speed: " .. math.max(velocity, customVelocity) .. ")")
end
end
end
humanoidRootPart.Touched:Connect(onPartTouched)
end
game.Players.LocalPlayer.CharacterAdded:Connect(onCharacterAdded)
While this does work somewhat as intended, results are extremely inaccurate and fluctuate massively. I’ve tested the same method of tracking velocity on unanchored parts, and when the AssemblyLinearVelocity is a constant value, the CustomVelocity that this script calculates will be around 3-5 studs inaccurate but constantly fluctuating around the actual value.
If anyone has any solutions for this it would be much appreciated.