How does my hit reg look?

How is my hit reg? im not sure how well its doing since my friend at 150 ping was testing it with a toggleable aimbot thing I made to test it perfectly & he said it wasnt hitting all the time, but for me at 50 ping manualy aiming it worked, however thats low ping,

Heres the script, it basicly sends the fastCast data from the client & validates it on the server, im looking for responsiveness improvements.

local HttpService = game:GetService("HttpService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local shootRemote = ReplicatedStorage["ORIS Gun Engine"].Remotes.ShootWeapon
local shotRepRemote = ReplicatedStorage["ORIS Gun Engine"].Remotes.ShotReplication
local hitRemote = ReplicatedStorage["ORIS Gun Engine"].Remotes.ProjectileHit

local DestructionModule = require(script.Destruction)
--local FastCastModule = require(script.FastCastRedux)

local Players = game:GetService("Players")

local glassTrans = {}


local debugCasts = false



local activeBullets = {}


--g gravity, v velocity, t time, p initial position
local function projectileMotionEquation(g, v0, p0, t, drag)
	-- drag: positive scalar, e.g. 0.1 for mild drag

	local k = drag
	if k == 0 then
		-- fallback to normal quadratic motion
		return 0.5 * g * t^2 + v0 * t + p0
	end

	-- Solve analytically with linear drag
	local term1 = (v0 - g / k) * (1 - math.exp(-k * t)) / k
	local term2 = (g * t) / k
	return p0 + term1 + term2
end


-- Raycast along path using analytic positions, with debug visualization
local function raycastAlongQuadraticPath(g, v0, p0, endTime, raycastParams, stepDistance, drag, debug)
	stepDistance = stepDistance or 1.5
	local maxStepsPerSecond = 240
	local minDt = 0.0005
	local maxDt = 0.033

	local t = 0
	local lastPos = projectileMotionEquation(g, v0, p0, 0, drag)

	if not endTime or endTime <= 0 then
		return nil
	end

	while t < endTime do
		local currentSpeed
		if drag == 0 or not drag then
			local velApprox = v0 + g * t
			currentSpeed = velApprox.Magnitude
		else
			local k = drag
			local velVec = (g / k) + (v0 - g / k) * math.exp(-k * t)
			currentSpeed = velVec.Magnitude
		end

		local dt
		if currentSpeed > 1e-4 then
			dt = stepDistance / currentSpeed
		else
			dt = maxDt
		end

		dt = math.clamp(dt, 1 / maxStepsPerSecond, maxDt)

		local nextT = math.min(endTime, t + dt)
		local nextPos = projectileMotionEquation(g, v0, p0, nextT, drag)
		local direction = nextPos - lastPos

		if direction.Magnitude > 0 then
			local rayResult = workspace:Raycast(lastPos, direction, raycastParams)
			if debug then
				-- debug parts
				local part = Instance.new("Part")
				part.Size = Vector3.new(0.25, 0.25, 0.25)
				part.Position = nextPos
				part.Anchored = true
				part.CanCollide = false
				part.CanQuery = false
				part.Material = Enum.Material.Neon
				part.Color = Color3.new(1, 0, 0) -- red for sampled points
				part.Name = "RaycastDebugPoint"
				part.Parent = workspace
				-- optional auto destroy after some time
				--task.delay(5, function() part:Destroy() end)

				-- draw a line from lastPos to nextPos
				local distance = (nextPos - lastPos).Magnitude
				if distance > 0 then
					local mid = (lastPos + nextPos) / 2
					local beam = Instance.new("Part")
					beam.Size = Vector3.new(0.1, 0.1, distance)
					beam.Anchored = true
					beam.CanCollide = false
					beam.CanQuery = false
					beam.Material = Enum.Material.Neon
					beam.Color = Color3.new(0, 1, 0) -- green for segments
					beam.CFrame = CFrame.new(mid, nextPos) * CFrame.new(0,0,-distance/2)
					beam.Parent = workspace
					--task.delay(5, function() beam:Destroy() end)
				end
			end

			if rayResult then
				return rayResult
			end
		end

		lastPos = nextPos
		t = nextT
	end

	return nil
end



local bulletExpireTime = 30
local timeIncrementToVelocityRatio = 0.05/1500 -- balance iteration count and velocity speed accuracy

local function pointToQuadraticClosestPointAproximation(point, g, v0, p0, endTime, drag)
	-- use small fixed dt for search accuracy (tune if necessary)
	local dt = 0.002 -- 2 ms steps; increase to 0.005 for performance
	local bestDistance = (point - projectileMotionEquation(g, v0, p0, 0, drag)).Magnitude
	local bestVector = point - projectileMotionEquation(g, v0, p0, 0, drag)
	local bestT = 0

	local t = dt
	while t <= math.min(endTime, bulletExpireTime) do
		local pos = projectileMotionEquation(g, v0, p0, t, drag)
		local vec = point - pos
		local dist = vec.Magnitude
		if dist < bestDistance then
			bestDistance = dist
			bestVector = vec
			bestT = t
		else
			-- if distance started increasing, we could break — but due to sampling noise we continue a little
			-- break -- optional early exit (careful)
		end
		t = t + dt
	end

	return bestDistance, bestVector, bestT
end




--[[local Caster = FastCastModule.new()
local CasterBehav = FastCastModule.newBehavior()

local TracerFolder = workspace:FindFirstChild("Tracers") or Instance.new("Folder", workspace)
TracerFolder.Name = "Tracers"


Caster.LengthChanged:Connect(function(ActiveCast, lastPoint, rayDir, displacement, Velocity, cosmeticBulletObject)
    ActiveCast:SetVelocity( ActiveCast:GetVelocity() * (1 - ActiveCast.WeaponData.Stats.ProjectileDrag) )

    cosmeticBulletObject.CFrame = CFrame.new(ActiveCast:GetPosition())
end)


Caster.RayHit:Connect(function(casterThatFired, RayCastResult, segmentVelocity, cosmeticBulletObject)

    local player = casterThatFired.PlayerFired
    local WeaponCartridge = casterThatFired.Cartridge

    cosmeticBulletObject:Destroy()

    if not player or not WeaponCartridge then return end


    if RayCastResult then
        local hitPart = RayCastResult.Instance

        DestructionModule:Shoot(RayCastResult.Position)


        if hitPart.Material == Enum.Material.Glass then
            glassTrans[hitPart] = hitPart.Transparency
            hitPart.Transparency = 1

            hitPart.ParticleEmitter:Emit(100)

            hitPart.CanCollide = false
            hitPart.CanTouch = false
            hitPart.CanQuery = false
            hitPart.AudioCanCollide = false


            task.delay(60,function()
                hitPart.Transparency = glassTrans[hitPart]

                hitPart.CanCollide = true
                hitPart.CanTouch = true
                hitPart.CanQuery = true
                hitPart.AudioCanCollide = true
            end)
        end


        local HitEffect = WeaponCartridge.Parent.HitEffect:Clone()
        HitEffect.Position = RayCastResult.Position
        HitEffect.Parent = workspace.HitEffects

        local children = HitEffect.HitSound:GetChildren()
        children[math.random(1, #children)]:Play()

        for _, particle in HitEffect.HitParticle:GetChildren() do
            if particle:IsA("ParticleEmitter") then
            particle.Color = ColorSequence.new(RayCastResult.Instance.Color)
            end
        end


        local character = hitPart:FindFirstAncestorOfClass("Model")
        if character and character:FindFirstChild("Humanoid") and character ~= player.character then
            if Players:GetPlayerFromCharacter(character) then
                if player.Team == Players:GetPlayerFromCharacter(character).Team then return end
                if player.Team == "Neutral" then return end
                if Players:GetPlayerFromCharacter(character).Team == "Neutral" then return end
            end

            local Damage = 0

            if hitPart.Name == "Left Leg" or hitPart.Name == "Right Leg" then
                Damage = WeaponCartridge.Leg.Value
            elseif hitPart.Name == "Left Arm" or hitPart.Name == "Right Arm" then
                Damage = WeaponCartridge.Arm.Value
            elseif hitPart.Name == "Torso" or hitPart.Name == "HumanoidRootPart" then
                Damage = WeaponCartridge.Torso.Value
            elseif hitPart.Name == "Head" then
                Damage = WeaponCartridge.Head.Value
            end

            local currentSpeed = segmentVelocity.Magnitude
            local speedRatio = math.clamp(currentSpeed / casterThatFired.WeaponData.Stats.ProjectileVelocity, 0, 1)

            Damage = Damage * (speedRatio ^ casterThatFired.WeaponData.Stats.ProjectileDmgFallOffExponent)
            print(Damage, hitPart.Name)

            for _, particle in HitEffect.HitParticle:GetChildren() do
                if particle:IsA("ParticleEmitter") then
                    particle.Color = ColorSequence.new(Color3.new(0.521568, 0.090196, 0.090196))
                end
            end

            character.Humanoid:TakeDamage(Damage)
        end


        for _, particle in HitEffect.HitParticle:GetChildren() do
            if particle:IsA("ParticleEmitter") then
                task.wait()
                particle:Emit(particle:GetAttribute("EmitCount"))
            end
        end

        task.delay(5, function()
            HitEffect:Destroy()
        end)
    end
end)]]



local function applySpread(direction, spread)
    -- spread.X = horizontal, spread.Y = vertical
    local randX = (math.random() - 0.5) * 2 * spread.X
    local randY = (math.random() - 0.5) * 2 * spread.Y

    -- Rotate the direction by random angles
    local cf = CFrame.new(Vector3.zero, direction) -- forward CFrame
    cf = cf * CFrame.Angles(randY, randX, 0)

    return cf.LookVector
end



shootRemote.OnServerInvoke = function(player, origin, direction)

    local plrCharacter = player.character
    if not plrCharacter then return end

    local Weapon = plrCharacter:FindFirstChildOfClass("Tool")
    if not Weapon then return end
    local WeaponData = require(Weapon.Data)
    --local WeaponTracer = Weapon.Tracer.Value

    local ammo = Weapon.Ammo
    if not ammo then return end

    local mag = ammo.Loaded:FindFirstChildOfClass("IntValue")
    if not mag then return end

    if mag.Value <= 0 then return end
    mag.Value -= 1

    local bulletId = HttpService:GenerateGUID(false)

    local thirdPersonModelName = Weapon.ThirdPersonModel.Value.Name
    activeBullets[bulletId] = {
        player = player,
        origin = plrCharacter.Head.Position,
        direction = direction,
        velocity = direction * WeaponData.Stats.ProjectileVelocity,
        gravity = Vector3.new(0, -workspace.Gravity * WeaponData.Stats.ProjectileGravityMult, 0),
        drag = WeaponData.Stats.ProjectileDrag,
        weaponData = WeaponData,
        thirdPersonModelName = thirdPersonModelName,

        cleanupThread = task.delay(30, function()
            activeBullets[bulletId] = nil
        end)
    }

    local TracerData = {
        origin = activeBullets[bulletId].origin
    }

    shotRepRemote:FireAllClients(player, thirdPersonModelName, TracerData)

    return bulletId

    --[[local WeaponCartridge = WeaponData.Stats.Cartridge


    local direction = applySpread(position.LookVector, WeaponData.Stats.ProjectileSpread)


    local params = RaycastParams.new()
    params.FilterType = Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances = {player.character}


    CasterBehav.RaycastParams = params
    CasterBehav.MaxDistance = WeaponData.Stats.Range
    CasterBehav.Acceleration = Vector3.new(0, -workspace.Gravity * WeaponData.Stats.ProjectileGravityMult, 0)
    
    CasterBehav.CosmeticBulletContainer = TracerFolder
    CasterBehav.CosmeticBulletTemplate = WeaponTracer


    Caster.VisualizeCasts = debugCasts
    FastCastModule.VisualizeCasts = debugCasts


    local position = plrCharacter:FindFirstChild("Head")

    local ray = Caster:Fire(position.Position, direction, WeaponData.Stats.ProjectileVelocity, CasterBehav)
    ray.PlayerFired = player
    ray.Cartridge = WeaponCartridge
    ray.WeaponData = WeaponData
    --ray.WeaponTracer = WeaponTracer

    shootRemote:FireAllClients(player, Weapon.ThirdPersonModel.Value.Name)]]
end


local hitPartDamage = {
    ["Head"] = "Head",
    ["Torso"] = "Torso",
    ["Left Leg"] = "Leg",
    ["Right Leg"] = "Leg",
    ["Left Arm"] = "Arm",
    ["Right Arm"] = "Arm"
}

local function getPartFromFullPath(path)
    local segments = string.split(path, ".")
    local current = game
    for _, segment in ipairs(segments) do
        current = current:FindFirstChild(segment)
        if not current then return nil end
    end
    return current
end


local function debugServerRay ( serverResult )
    if serverResult then
        local hitPos = serverResult[#serverResult]

        -- Create a debug part
        local debugPart = Instance.new("Part")
        debugPart.Size = Vector3.new(0.5, 0.5, 0.5)
        debugPart.Position = hitPos
        debugPart.Anchored = true
        debugPart.CanCollide = false
        debugPart.CanQuery = false
        debugPart.Color = Color3.new(1, 0, 0)
        debugPart.Material = Enum.Material.Neon
        debugPart.Parent = workspace
        debugPart.Name = "debug"

        --[[task.delay(5, function()
            debugPart:Destroy()
        end)]]
    end
end


local function validateFastCast(initPos, initVel, flightTime, drag, acceleration, params, world, firstSegmentLength, lastSegmentLength)
    --[[local highFidelitySize = math.max(firstSegmentLength, 0.001) -- avoid zero

    local position = initPos
    local velocity = initVel
    local segmentPoints = {position}

    local timeElapsed = 0
    local minDt = 0.01 -- prevent tiny steps
    local maxDt = 0.05 -- cap for slow bullets

    while timeElapsed < flightTime do
        local speed = velocity.Magnitude
        if speed < 1e-5 then break end

        -- Dynamic dt: distance / speed, clamped
        local dt = highFidelitySize / speed
        dt = math.clamp(dt, minDt, maxDt)

        -- Clamp last segment to client-reported length
        if flightTime - timeElapsed <= dt then
            -- Calculate dt so the last segment matches lastSegmentLength
            if lastSegmentLength then
                dt = lastSegmentLength / math.max(speed, 1e-5)
            else
                dt = flightTime - timeElapsed
            end
        end

        dt = math.min(dt, flightTime - timeElapsed)

        -- Apply acceleration
        velocity = velocity + acceleration * dt

        -- Apply drag
        velocity = velocity * (1 - drag)

        -- Predict next position
        local nextPos = position + velocity * dt
        local displacement = nextPos - position

        -- Raycast
        local result = world:Raycast(position, displacement, params)
        if result then
            nextPos = result.Position
        end

        -- Visualize
        local cone = Instance.new("ConeHandleAdornment")
        cone.Adornee = workspace.Terrain
        cone.CFrame = CFrame.new(position, nextPos)
        cone.Height = displacement.Magnitude
        cone.Radius = 0.2
        cone.Transparency = 0.5
        cone.Color3 = Color3.new(1, 0, 0)
        cone.Parent = workspace.Terrain

        position = nextPos
        table.insert(segmentPoints, position)
        timeElapsed = timeElapsed + dt

        if result then break end
    end

    return segmentPoints]]
end

local function validateFastCastFromClientData(initPos, segmentData, params, world)
    local position = initPos
    local segmentPoints = {position}

    local result

    for i, segment in ipairs(segmentData) do
        local velocity = segment.Velocity
        local length = segment.Length

        -- Sanity check
        if typeof(velocity) ~= "Vector3" or type(length) ~= "number" then
            warn(`[FastCast Validate] Invalid segment data at index {i}`)
            break
        end

        local speed = velocity.Magnitude
        if speed < 1e-4 or length <= 0 then
            warn(`[FastCast Validate] Zero-length or zero-velocity at segment {i}`)
            break
        end

        -- Compute dt and displacement
        local dt = length / speed
        local displacement = velocity.Unit * length
        local nextPos = position + displacement

        -- Raycast for hits
        result = world:Raycast(position, displacement, params)
        if result then
            nextPos = result.Position
        end

        -- Debug visualize segment as a line
        local beam = Instance.new("Part")
        beam.Anchored = true
        beam.CanCollide = false
        beam.Material = Enum.Material.Neon
        beam.Color = Color3.new(1, 0, 0)
        beam.Size = Vector3.new(0.05, 0.05, displacement.Magnitude)
        beam.CFrame = CFrame.new(position, nextPos) * CFrame.new(0, 0, -displacement.Magnitude / 2)
        beam.Parent = workspace
        --game:GetService("Debris"):AddItem(beam, 5)

        position = nextPos
        table.insert(segmentPoints, position)

        if result then break end
    end

    return segmentPoints, result
end


local function findClosestPointInList(pointList, target)
    local bestIdx = nil
    local bestPoint = nil
    local bestDist = math.huge

    for i = 1, #pointList do
        local p = pointList[i]
        local d = (p - target).Magnitude
        if d < bestDist then
            bestDist = d
            bestPoint = p
            bestIdx = i
        end
    end

    return bestIdx, bestPoint, bestDist
end



hitRemote.OnServerEvent:Connect(function(player, bulletId, flightTime, clientHitPosition, clientHitPart, SegmentData)

    local data = activeBullets[bulletId]
    if not data then return end
    if data.player ~= player then return end

    local weaponData = data.weaponData
    local gravity = data.gravity
    local velocity = data.velocity
    local origin = data.origin
    --local timeAlive = timeStamp - data.startTime
    local thirdPersonModelName = data.thirdPersonModelName
    local drag = data.drag
    --flightTime = flightTime + 0.3


    if (origin - player.character.Head.Position).Magnitude > 5 then
        warn("Client is cheating their shot position!")
        return
    end


    local params = RaycastParams.new()
    params.FilterType = Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances = {player.character}

    print(flightTime)

    --[[local serverResult = validateFastCast(
        origin,
        velocity,
        flightTime,
        drag,
        gravity,
        params,
        workspace,
        SegmentLength[1].Length,
        SegmentLength[#SegmentLength].Length
    )]]

    local serverResult, serverHit = validateFastCastFromClientData(
        player.character.Head.Position,
        SegmentData,
        params,
        workspace
    )

    --debugServerRay(serverResult)


    if not serverResult then
        warn(player.Name .. " Reported a hit, but server simulation found no collision")
        return
    end


    --local distance = (serverResult.Position - clientHitPosition).Magnitude

    --[[local distance, _, _ = pointToQuadraticClosestPointAproximation(
        serverResult.Position,
        gravity,
        velocity,
        origin,
        flightTime,
        drag
    )]]

    local _, _, closestPoint = findClosestPointInList(serverResult, clientHitPosition)


    if closestPoint > 15 then
        print(("%s invalid hit: %.2f studs off path"):format(player.Name, closestPoint))
        return
    end

    local weaponCart = weaponData.Stats.Cartridge
    if not weaponCart then
        warn("No weapon cartridge ¯\_(ツ)_/¯")
        return
    end

    local character = clientHitPart:FindFirstAncestorOfClass("Model")
    if character and character:FindFirstChild("Humanoid") then
        print(clientHitPart.Name)
        local region = hitPartDamage[clientHitPart.Name]
        if region then
            local damage = weaponCart[region].Value
            character.Humanoid:TakeDamage(damage)

            --[[if clientHitPart.Material == Enum.Material.Glass then
                
            end]]

            --shotRepRemote:FireAllClients(player, thirdPersonModelName)
        else
            warn("No hit region. Aim better ( ͡° ͜ʖ ͡°)")
            return
        end
    end

    task.cancel(activeBullets[bulletId].cleanupThread)
    activeBullets[bulletId] = nil
end)

thanks

2 Likes