You can write your topic however you want, but you need to answer these questions:
- What do you want to achieve? Keep it simple and clear!
it starts snapping in the actual game but it doesnt in the studio gameplay
- What is the issue? Include screenshots / videos if possible!
- What solutions have you tried so far? Did you look for solutions on the Creator Hub?
i couldnt find any topics related to this
After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
-- This is an entire luau block
– Services
local Workspace = game:GetService(“Workspace”)
local RunService = game:GetService(“RunService”)
local Players = game:GetService(“Players”)
– Excluded NPC names (add more as needed)
local excludedNames = {
[“Sientist”] = true,
[“Thomas”] = true,
}
– Configuration
local SoundService = game:GetService(“SoundService”)
local shooterPart = script.Parent
local camRig = shooterPart.Parent – CamRig containing AnimationController
local animationId = “rbxassetid://117122820104386” – Updated animation ID
– Box detection configuration
local detectionBoxSize = Vector3.new(500, 300, 800) – Width, Height, Depth (larger forward range)
local detectionBoxOffset = Vector3.new(0, 0, 0) – Offset forward from camera
local minDetectionDistance = 10 – Minimum distance to detect NPCs
local maxDetectionDistance = 100 – Maximum detection distance
local detectionUpdateRate = 0.1 – Check every 0.1 seconds (10 times per second)
– Smoothing configuration (SLOW AND DELAYED)
local baseLookSpeed = 1 – Much slower base speed
local initialLookSpeed = 0.01 – Very slow initial speed for dramatic delay
local lookSpeedRampTime = 5 – Longer ramp-up time for delayed effect
local maxLookSpeed = 0.04 – Cap the maximum look speed (slow tracking)
local resumeTransitionTime = 1.5 – Smooth resume transition
local damageAmount = 0 – Set to 20 for damage
local deathDelay = 1 – Seconds after NPC death
local Sounds = {
Tragedy = SoundService:WaitForChild(“Tragedy”)
}
– Animation setup with better error handling
local animation = Instance.new(“Animation”)
animation.AnimationId = animationId
animation.Parent = camRig
animation.Name = “CameraPath”
– Find AnimationController or Humanoid
local animationController = camRig:FindFirstChildOfClass(“AnimationController”) or camRig:FindFirstChildOfClass(“Humanoid”)
if not animationController then
warn(“[ERROR] No AnimationController or Humanoid in CamRig”)
return
end
– Get or create Animator
local animator = animationController:FindFirstChildOfClass(“Animator”)
if not animator then
animator = Instance.new(“Animator”)
animator.Parent = animationController
task.wait(0.1) – Give time for Animator to initialize
end
– Load animation with retry logic
local animationTrack = nil
local maxRetries = 5
local retryDelay = 0.5
for i = 1, maxRetries do
local success, result = pcall(function()
return animator:LoadAnimation(animation)
end)
if success and result then
animationTrack = result
print("[SUCCESS] Animation loaded on attempt", i)
break
else
warn("[RETRY] Failed to load animation, attempt", i, "Error:", result)
if i < maxRetries then
task.wait(retryDelay)
end
end
end
if not animationTrack then
warn(“[ERROR] Failed to load animation after”, maxRetries, “attempts”)
return
end
– Wait for animation to be fully loaded
task.wait(0.2)
local defaultAnimationSpeed = 1
– Variables
local detectedNPC = nil
local targetNPC = nil
local lookConnection = nil
local npcConnection = nil
local resumeConnection = nil
local lastCFrame = shooterPart.CFrame
local originalCFrame = shooterPart.CFrame
local preTargetCFrame = shooterPart.CFrame
local lookStartTime = nil
local resumeStartTime = nil
local isTargeting = false
local isResuming = false
local stopKeyframeReached = false
local preStopDetectionActive = false – NEW: Allow detection right before stop
local stopRequested = false
local canDetectNPCs = true
local lastDetectionTime = 0
local markerConnectionsActive = false
– Detection box visualization (optional, for debugging)
local detectionBox = nil
local showDebugBox = false – Set to true to visualize the detection box
if showDebugBox then
detectionBox = Instance.new(“Part”)
detectionBox.Name = “DetectionBox”
detectionBox.Size = detectionBoxSize
detectionBox.Transparency = 0.5
detectionBox.Color = Color3.fromRGB(255, 0, 0)
detectionBox.CanCollide = false
detectionBox.Anchored = true
detectionBox.Material = Enum.Material.Neon
detectionBox.Parent = Workspace
end
– Function to check if NPC exists
local function isNPCInWorkspace(npc)
return npc and npc.Parent and npc:IsDescendantOf(Workspace)
end
– Function to check if NPC can be looked at
local function canLookAtNPC(npc)
if not npc then return false end
local canLookValue = npc:FindFirstChild(“CanLook”)
if canLookValue and canLookValue:IsA(“BoolValue”) then
return canLookValue.Value
else
return false
end
end
– Function to get NPC look-at part (focuses on UpperTorso)
local function getLookAtPart(npc)
local humanoid = npc:FindFirstChildOfClass(“Humanoid”)
if humanoid then
local rigType = humanoid.RigType
– Prioritize UpperTorso for R15, Torso for R6
if rigType == Enum.HumanoidRigType.R15 then
local upperTorso = npc:FindFirstChild(“UpperTorso”)
if upperTorso then return upperTorso end
else
local torso = npc:FindFirstChild(“Torso”)
if torso then return torso end
end
end
-- Fallback to HumanoidRootPart if torso not found
local hrp = npc:FindFirstChild("HumanoidRootPart")
if hrp then return hrp end
return nil
end
– Spawn Virgil function
local function spawnvirgil(param)
print(“[MARKER] SpawnVirgil1 fired! Param:”, param)
local virgil = game:GetService(“ServerStorage”).Creatures:FindFirstChild(“Cyril”)
if not virgil then
warn(“No BO_Cyril in ServerStorage”)
return
end
local virgilClone = virgil:Clone()
virgilClone.Parent = workspace
if param and param ~= "" then
local values = string.split(param, ",")
for i, v in ipairs(values) do
values[i] = tonumber(v)
end
if #values == 12 then
local cf = CFrame.new(
values[1], values[2], values[3],
values[4], values[5], values[6],
values[7], values[8], values[9],
values[10], values[11], values[12]
)
virgilClone:WaitForChild("HumanoidRootPart").CFrame = cf
elseif #values == 3 then
virgilClone:WaitForChild("HumanoidRootPart").CFrame = CFrame.new(values[1], values[2], values[3])
else
warn("Param did not have 3 or 12 numbers, got:", #values)
end
else
warn("No param given for VirgilSpawn1 marker")
end
end
– Play tragedy sound
local function PlayTragedy()
print(“[MARKER] Tragedy marker fired”)
Sounds.Tragedy:Play()
end
local function PlayCarScene()
print(“[MARKER] CarScene marker fired”)
game:GetService(“ReplicatedStorage”):FindFirstChild(“CarSceneEvent”):Fire()
end
– Function to clean up targeting connections
local function cleanupTargeting()
if lookConnection then
lookConnection:Disconnect()
lookConnection = nil
end
if npcConnection then
npcConnection:Disconnect()
npcConnection = nil
end
targetNPC = nil
lookStartTime = nil
isTargeting = false
end
– Function to resume animation with smooth transition
local function resumeAnimation()
print(“[RESUME] Starting animation resume”)
cleanupTargeting()
isResuming = true
resumeStartTime = tick()
stopKeyframeReached = false – Reset for next stop keyframe
preStopDetectionActive = false – Reset pre-detection
stopRequested = false
detectedNPC = nil – Clear detected NPC
local startTransitionCFrame = lastCFrame
if shooterPart and shooterPart.Parent and animationTrack then
pcall(function()
animationTrack:AdjustSpeed(0)
end)
shooterPart.Anchored = true
end
if resumeConnection then resumeConnection:Disconnect() end
resumeConnection = RunService.Heartbeat:Connect(function(deltaTime)
local elapsed = tick() - resumeStartTime
local progress = math.min(elapsed / resumeTransitionTime, 1)
-- Smoother easing with cubic interpolation (for delayed feel)
local easedProgress = progress * progress * (3 - 2 * progress)
local transitionCFrame = startTransitionCFrame:Lerp(preTargetCFrame, easedProgress)
shooterPart.CFrame = transitionCFrame
lastCFrame = transitionCFrame
shooterPart.AssemblyLinearVelocity = Vector3.zero
shooterPart.AssemblyAngularVelocity = Vector3.zero
if progress >= 1 then
if resumeConnection then
resumeConnection:Disconnect()
resumeConnection = nil
end
isResuming = false
print("[RESUME] Animation resume complete")
if shooterPart and shooterPart.Parent and animationTrack then
shooterPart.Anchored = false
pcall(function()
animationTrack:AdjustSpeed(defaultAnimationSpeed)
end)
shooterPart.AssemblyLinearVelocity = Vector3.zero
shooterPart.AssemblyAngularVelocity = Vector3.zero
end
end
end)
end
– Improved smooth look-at function
local function lookAtNPC(deltaTime)
if not isTargeting then return end
if targetNPC and isNPCInWorkspace(targetNPC) then
local lookPart = getLookAtPart(targetNPC)
local humanoid = targetNPC:FindFirstChildOfClass("Humanoid")
if lookPart and humanoid then
if humanoid.Health <= 0 then
resumeAnimation()
return
end
if shooterPart.Anchored then
local shooterPos = shooterPart.Position
local npcPos = lookPart.Position
local targetCFrame = CFrame.new(shooterPos, npcPos)
local elapsed = lookStartTime and (tick() - lookStartTime) or 0
local rampFactor = math.min(elapsed / lookSpeedRampTime, 1)
-- Smoothstep easing for natural delayed acceleration
local easedRampFactor = rampFactor * rampFactor * (3 - 2 * rampFactor)
local currentLookSpeed = initialLookSpeed + (baseLookSpeed - initialLookSpeed) * easedRampFactor
currentLookSpeed = math.min(currentLookSpeed, maxLookSpeed)
local currentLookVector = lastCFrame.LookVector
local targetLookVector = targetCFrame.LookVector
local angleDiff = math.acos(math.clamp(currentLookVector:Dot(targetLookVector), -1, 1))
-- Smoother proximity adjustment with delayed response
local proximityFactor = math.max(0.3, angleDiff / math.pi)
local adjustedLookSpeed = currentLookSpeed * proximityFactor
-- Frame-rate independent with delayed interpolation
local lerpAlpha = math.clamp(adjustedLookSpeed * deltaTime * 60, 0, 0.1)
local currentRot = lastCFrame - lastCFrame.Position
local targetRot = targetCFrame - targetCFrame.Position
local slerpRot = currentRot:Lerp(targetRot, lerpAlpha)
lastCFrame = CFrame.new(shooterPos) * slerpRot
shooterPart.CFrame = lastCFrame
shooterPart.AssemblyLinearVelocity = Vector3.zero
shooterPart.AssemblyAngularVelocity = Vector3.zero
end
else
resumeAnimation()
end
else
resumeAnimation()
end
end
– Function to start targeting
local function startTargeting(npc)
if not npc or not isNPCInWorkspace(npc) then
print(“[TARGET] Invalid NPC, cannot start targeting”)
detectedNPC = nil
return
end
print("[TARGET] Starting targeting for:", npc.Name)
targetNPC = npc
detectedNPC = nil
isTargeting = true
preTargetCFrame = shooterPart.CFrame
pcall(function()
animationTrack:AdjustSpeed(0)
end)
task.wait()
shooterPart.Anchored = true
shooterPart.AssemblyLinearVelocity = Vector3.zero
shooterPart.AssemblyAngularVelocity = Vector3.zero
lastCFrame = shooterPart.CFrame
lookStartTime = tick()
local humanoid = npc:FindFirstChildOfClass("Humanoid")
if humanoid and damageAmount > 0 then
humanoid:TakeDamage(damageAmount)
end
if lookConnection then lookConnection:Disconnect() end
lookConnection = RunService.Heartbeat:Connect(function(deltaTime)
lookAtNPC(deltaTime)
end)
if npcConnection then npcConnection:Disconnect() end
npcConnection = Workspace.DescendantRemoving:Connect(function(descendant)
if descendant == targetNPC or (targetNPC and descendant:IsAncestorOf(targetNPC)) then
resumeAnimation()
end
end)
end
– Function to handle stop keyframe reached
local function onStopKeyframe()
stopKeyframeReached = true
preStopDetectionActive = false – Stop pre-detection
print(“[MARKER] Stop keyframe reached”)
-- ONLY start targeting if we have a detected NPC
if detectedNPC then
print("[MARKER] Starting targeting for detected NPC:", detectedNPC.Name)
startTargeting(detectedNPC)
else
print("[MARKER] No NPC detected at stop keyframe, waiting for detection...")
end
end
– NEW: Function to handle pre-stop marker (add this marker ~0.5 seconds before “stop”)
local function onPreStopKeyframe()
preStopDetectionActive = true
print(“[MARKER] PreStop keyframe reached - detection now active”)
end
– Box-based NPC detection using Region3
local function scanForTargets()
– CRITICAL: Do not detect if we’re already targeting or resuming
if isTargeting or isResuming then
return
end
-- Only detect during pre-stop window or after stop keyframe is reached
if not preStopDetectionActive and not stopKeyframeReached then
return
end
-- If we already have a detected NPC waiting, don't scan again
if detectedNPC then
return
end
-- Throttle detection checks
local currentTime = tick()
if currentTime - lastDetectionTime < detectionUpdateRate then
return
end
lastDetectionTime = currentTime
-- Calculate detection box position and orientation
local boxCFrame = shooterPart.CFrame * CFrame.new(detectionBoxOffset)
-- Update debug box position
if showDebugBox and detectionBox then
detectionBox.CFrame = boxCFrame
end
-- Use OverlapParams for more efficient detection
local overlapParams = OverlapParams.new()
overlapParams.FilterType = Enum.RaycastFilterType.Blacklist
overlapParams.FilterDescendantsInstances = {shooterPart, camRig}
-- Get all parts in the region
local partsInRegion = Workspace:GetPartBoundsInBox(boxCFrame, detectionBoxSize, overlapParams)
local bestTarget = nil
local bestScore = -math.huge
for _, part in ipairs(partsInRegion) do
local character = part.Parent
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
local isPlayer = Players:GetPlayerFromCharacter(character) ~= nil
local isExcluded = excludedNames[character and character.Name] == true
if humanoid and humanoid.Health > 0 and not isPlayer and not isExcluded then
if canLookAtNPC(character) then
local lookPart = getLookAtPart(character)
if lookPart then
local distance = (shooterPart.Position - lookPart.Position).Magnitude
if distance >= minDetectionDistance and distance <= maxDetectionDistance then
-- Calculate how centered the target is
local targetDirection = (lookPart.Position - shooterPart.Position).Unit
local dotProduct = shooterPart.CFrame.LookVector:Dot(targetDirection)
-- Score based on being centered and close
local centerScore = dotProduct * 100 -- Higher when more centered
local distanceScore = (maxDetectionDistance - distance) / maxDetectionDistance * 50 -- Closer is better
local totalScore = centerScore + distanceScore
if totalScore > bestScore then
bestTarget = character
bestScore = totalScore
end
end
end
end
end
end
if bestTarget then
print("[DETECTION] Target detected:", bestTarget.Name, "Score:", bestScore)
detectedNPC = bestTarget
-- Only start targeting immediately if stop keyframe already reached
if stopKeyframeReached then
print("[DETECTION] Stop already reached, starting targeting immediately")
startTargeting(detectedNPC)
else
print("[DETECTION] Waiting for stop keyframe before targeting")
end
end
end
– Store original CFrame
originalCFrame = shooterPart.CFrame
– Start animation with proper error handling
print(“[INIT] Starting animation…”)
local playSuccess, playErr = pcall(function()
animationTrack:Play()
animationTrack:AdjustSpeed(defaultAnimationSpeed)
end)
if not playSuccess then
warn(“[ERROR] Animation failed to start:”, playErr)
return
end
print(“[INIT] Animation playing, waiting for it to load…”)
task.wait(0.5) – Give animation time to fully initialize
– Connect marker events with error handling
local function connectMarkerSafely(markerName, callback)
local success, connection = pcall(function()
return animationTrack:GetMarkerReachedSignal(markerName):Connect(callback)
end)
if success then
print("[MARKER] Connected to marker:", markerName)
return connection
else
warn("[ERROR] Failed to connect to marker:", markerName, connection)
return nil
end
end
– Connect all markers
connectMarkerSafely(“SpawnVirgil1”, spawnvirgil)
connectMarkerSafely(“PreStop”, onPreStopKeyframe) – NEW: Connect PreStop marker
connectMarkerSafely(“stop”, onStopKeyframe)
connectMarkerSafely(“Tragedy”, PlayTragedy)
connectMarkerSafely(“PlayCarScene”, PlayCarScene)
markerConnectionsActive = true
print(“[INIT] All marker connections established”)
– Main detection loop
RunService.Heartbeat:Connect(function()
if markerConnectionsActive then
scanForTargets()
end
end)
– Cleanup
shooterPart.AncestryChanged:Connect(function()
if not shooterPart:IsDescendantOf(Workspace) then
if lookConnection then lookConnection:Disconnect() end
if npcConnection then npcConnection:Disconnect() end
if resumeConnection then resumeConnection:Disconnect() end
if animationTrack then
pcall(function()
animationTrack:Stop()
end)
end
if showDebugBox and detectionBox then
detectionBox:Destroy()
end
markerConnectionsActive = false
end
end)