Certainly! Enhancing your existing Advanced Dynamic Slap Blocking System can significantly improve user experience and the effectiveness of the anti-slap measures. Below, I've incorporated several advanced features to bolster the system:
- Per-Player Cooldowns: Instead of a global cooldown, each opponent has their own cooldown, allowing simultaneous interactions without interference.
- Sound and Visual Effects: Adds auditory and visual feedback when blocking or being blocked, enhancing immersion.
- Enhanced GUI: Provides more detailed information, including the number of active blocks and recent blocked interactions.
- Dynamic Block Strength: Adjusts blocking strength based on the distance of the opponent, making the system more adaptive.
- Notification System: Notifies players upon successful blocks or when the system is toggled.
- Robust Error Handling: Ensures smooth operation even when opponents leave mid-interaction or other edge cases occur.
- Configurable Settings: Offers more flexibility by allowing users to tweak various settings directly from the GUI.
Below is the improved script incorporating these features:
-- Enhanced Roblox Script with Advanced Dynamic Slap Blocking System and Toggle Feature
-- Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local VirtualInputManager = game:GetService("VirtualInputManager")
local TweenService = game:GetService("TweenService")
local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local SoundService = game:GetService("SoundService")
-- Remotes
local LightsaberRemotes = ReplicatedStorage:WaitForChild("LightsaberRemotes")
local BlockRemote = LightsaberRemotes:WaitForChild("Block")
local UnblockRemote = LightsaberRemotes:WaitForChild("Unblock")
-- Settings
local Settings = {
BlockDistance = 15,
AutoCounterEnabled = true,
AutoSlapDistance = 10,
ReactionTimeThreshold = 0.15, -- Base reaction time
BlockDuration = 0.3,
Cooldown = 1.0,
SlapAnimations = {
["Slap"] = 12625891544,
["SlappedLegs"] = 12671715182,
["SlappedArms"] = 12625896358,
["RightSwing"] = 12625891545,
["LeftSwing"] = 12625891546,
["OverheadSwing"] = 12625891547,
["DoubleSlap"] = 12625891548
},
Sounds = {
BlockSoundId = "rbxassetid://YourBlockSoundID", -- Replace with actual sound ID
CounterSoundId = "rbxassetid://YourCounterSoundID" -- Replace with actual sound ID
},
GUI = {
BlockIndicatorSize = UDim2.new(0, 250, 0, 120),
ToggleIndicatorSize = UDim2.new(0, 200, 0, 50),
NotificationSize = UDim2.new(0, 300, 0, 50),
NotificationDuration = 2, -- seconds
}
}
-- State Management
local blockingPlayers = {} -- { [PlayerName] = {LastBlockTime = number, BlockStartTime = number} }
local isBlockingEnabled = true
local notifications = {}
-- GUI Setup for Visual Feedback
local function setupGUI()
local screenGui = Instance.new("ScreenGui")
screenGui.Name = "AdvancedAntiSlapIndicator"
screenGui.ResetOnSpawn = false
screenGui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
-- Block Indicator
local blockIndicator = Instance.new("Frame")
blockIndicator.Size = Settings.GUI.BlockIndicatorSize
blockIndicator.Position = UDim2.new(0.5, -Settings.GUI.BlockIndicatorSize.X.Offset / 2, 0, 10)
blockIndicator.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
blockIndicator.BackgroundTransparency = 0.5
blockIndicator.BorderSizePixel = 0
blockIndicator.Visible = false
blockIndicator.Parent = screenGui
local blockText = Instance.new("TextLabel")
blockText.Size = UDim2.new(1, 0, 1, 0)
blockText.BackgroundTransparency = 1
blockText.Text = "Blocking System:\nEnabled\nActive Blocks: 0"
blockText.TextColor3 = Color3.fromRGB(255, 255, 255)
blockText.TextScaled = true
blockText.TextWrapped = true
blockText.Parent = blockIndicator
-- Toggle Indicator
local toggleIndicator = Instance.new("Frame")
toggleIndicator.Size = Settings.GUI.ToggleIndicatorSize
toggleIndicator.Position = UDim2.new(0.5, -Settings.GUI.ToggleIndicatorSize.X.Offset / 2, 0, 140)
toggleIndicator.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
toggleIndicator.BackgroundTransparency = 0.5
toggleIndicator.BorderSizePixel = 0
toggleIndicator.Visible = false
toggleIndicator.Parent = screenGui
local toggleText = Instance.new("TextLabel")
toggleText.Size = UDim2.new(1, 0, 1, 0)
toggleText.BackgroundTransparency = 1
toggleText.Text = "Blocking System Disabled"
toggleText.TextColor3 = Color3.fromRGB(255, 0, 0)
toggleText.TextScaled = true
toggleText.TextWrapped = true
toggleText.Parent = toggleIndicator
-- Notification Frame
local notificationFrame = Instance.new("Frame")
notificationFrame.Size = Settings.GUI.NotificationSize
notificationFrame.Position = UDim2.new(0.5, -Settings.GUI.NotificationSize.X.Offset / 2, 1, -Settings.GUI.NotificationSize.Y.Offset - 10)
notificationFrame.BackgroundColor3 = Color3.fromRGB(50, 50, 50)
notificationFrame.BackgroundTransparency = 0.7
notificationFrame.BorderSizePixel = 0
notificationFrame.Visible = false
notificationFrame.Parent = screenGui
local notificationText = Instance.new("TextLabel")
notificationText.Size = UDim2.new(1, -20, 1, 0)
notificationText.Position = UDim2.new(0, 10, 0, 0)
notificationText.BackgroundTransparency = 1
notificationText.Text = ""
notificationText.TextColor3 = Color3.fromRGB(255, 255, 255)
notificationText.TextScaled = true
notificationText.TextWrapped = true
notificationText.Parent = notificationFrame
return blockIndicator, blockText, toggleIndicator, toggleText, notificationFrame, notificationText
end
local blockIndicator, blockText, toggleIndicator, toggleText, notificationFrame, notificationText = setupGUI()
-- Tween Setup
local tweenInfoVisible = TweenInfo.new(0.2, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
local tweenInfoHidden = TweenInfo.new(0.2, Enum.EasingStyle.Quad, Enum.EasingDirection.In)
local showTween = TweenService:Create(blockIndicator, tweenInfoVisible, {BackgroundTransparency = 0.3, Visible = true})
local hideTween = TweenService:Create(blockIndicator, tweenInfoHidden, {BackgroundTransparency = 0.5, Visible = false})
local toggleShowTween = TweenService:Create(toggleIndicator, tweenInfoVisible, {BackgroundTransparency = 0.3, Visible = true})
local toggleHideTween = TweenService:Create(toggleIndicator, tweenInfoHidden, {BackgroundTransparency = 0.5, Visible = false})
local showNotificationTween = TweenService:Create(notificationFrame, TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {Position = UDim2.new(0.5, -Settings.GUI.NotificationSize.X.Offset / 2, 0.95, -Settings.GUI.NotificationSize.Y.Offset - 10), Visible = true})
local hideNotificationTween = TweenService:Create(notificationFrame, TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.In), {Position = UDim2.new(0.5, -Settings.GUI.NotificationSize.X.Offset / 2, 1, -Settings.GUI.NotificationSize.Y.Offset - 10), Visible = false})
-- Sounds Setup
local blockSound = Instance.new("Sound")
blockSound.SoundId = Settings.Sounds.BlockSoundId
blockSound.Volume = 1
blockSound.Parent = SoundService
local counterSound = Instance.new("Sound")
counterSound.SoundId = Settings.Sounds.CounterSoundId
counterSound.Volume = 1
counterSound.Parent = SoundService
-- Utility Functions
local function getCurrentTime()
return tick()
end
local function getClosestPlayers()
local players = {}
local localPlayer = Players.LocalPlayer
local localCharacter = localPlayer.Character
if localCharacter and localCharacter:FindFirstChild("HumanoidRootPart") then
local localPosition = localCharacter.HumanoidRootPart.Position
for _, player in ipairs(Players:GetPlayers()) do
if player ~= localPlayer and player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
local playerPosition = player.Character.HumanoidRootPart.Position
local distance = (playerPosition - localPosition).Magnitude
if distance <= Settings.BlockDistance then
table.insert(players, {Player = player, Distance = distance})
end
end
end
end
table.sort(players, function(a, b) return a.Distance < b.Distance end)
return players
end
local function updateGUI()
local activeBlocks = 0
for _, info in pairs(blockingPlayers) do
activeBlocks = activeBlocks + 1
end
if isBlockingEnabled then
if activeBlocks > 0 then
blockIndicator.Visible = true
blockText.Text = string.format("Blocking System:\nEnabled\nActive Blocks: %d", activeBlocks)
showTween:Play()
else
hideTween:Play()
blockText.Text = "Blocking System:\nEnabled\nActive Blocks: 0"
end
else
toggleHideTween:Play()
blockIndicator.Visible = false
blockText.Text = "Blocking System Disabled"
end
end
local function showNotification(message, isError)
notificationText.Text = message
notificationFrame.BackgroundColor3 = isError and Color3.fromRGB(200, 50, 50) or Color3.fromRGB(50, 200, 50)
showNotificationTween:Play()
task.delay(Settings.GUI.NotificationDuration, function()
hideNotificationTween:Play()
end)
end
local function toggleBlockingSystem()
isBlockingEnabled = not isBlockingEnabled
if isBlockingEnabled then
toggleIndicator.Visible = false
toggleHideTween:Play()
showNotification("Blocking System Enabled", false)
print("Blocking System Enabled")
else
toggleIndicator.Visible = true
toggleShowTween:Play()
blockingPlayers = {}
UnblockRemote:FireServer()
showNotification("Blocking System Disabled", true)
print("Blocking System Disabled")
end
updateGUI()
end
-- Enhanced Slap Animation Handling
local function handleSlapAnimation(opponent, animTrack)
if not isBlockingEnabled then return end
local localPlayer = Players.LocalPlayer
local character = localPlayer.Character
if not character or not character:FindFirstChild("HumanoidRootPart") then return end
local opponentRoot = opponent.Character:FindFirstChild("HumanoidRootPart")
if not opponentRoot then return end
local distance = (character.HumanoidRootPart.Position - opponentRoot.Position).Magnitude
if distance > Settings.BlockDistance then return end
local currentTime = getCurrentTime()
local opponentInfo = blockingPlayers[opponent.Name]
if opponentInfo then
if (currentTime - opponentInfo.LastBlockTime) < Settings.Cooldown then
print(string.format("Blocked recently by %s. Cooldown remaining: %.2f seconds", opponent.Name, Settings.Cooldown - (currentTime - opponentInfo.LastBlockTime)))
return
end
end
local dynamicReactionTime = Settings.ReactionTimeThreshold * (Settings.BlockDistance / math.max(distance,1))
dynamicReactionTime = math.clamp(dynamicReactionTime, 0.05, Settings.ReactionTimeThreshold)
local shouldBlock = false
local reactiveAnims = {"Slap", "RightSwing", "LeftSwing", "OverheadSwing", "DoubleSlap"}
for _, animName in ipairs(reactiveAnims) do
if animTrack.Animation.AnimationId == "rbxassetid://" .. Settings.SlapAnimations[animName] then
shouldBlock = true
break
end
end
if shouldBlock then
-- Initialize or update opponent's block info
blockingPlayers[opponent.Name] = {
LastBlockTime = currentTime,
BlockStartTime = currentTime
}
BlockRemote:FireServer(opponent)
blockSound:Play()
showNotification("Blocked a slap from " .. opponent.Name, false)
print("Blocking initiated against:", opponent.Name)
updateGUI()
task.delay(Settings.BlockDuration, function()
UnblockRemote:FireServer(opponent)
blockingPlayers[opponent.Name] = nil
print("Blocking ended for:", opponent.Name)
updateGUI()
end)
if Settings.AutoCounterEnabled and distance <= Settings.AutoSlapDistance then
task.delay(dynamicReactionTime, function()
VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.E, false, game)
task.wait(0.1)
VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.E, false, game)
counterSound:Play()
showNotification("Automatic counter-slap performed against " .. opponent.Name, false)
print("Automatic counter-slap performed against:", opponent.Name)
end)
end
end
end
-- Setup Functions
local function onOpponentAnimationPlayed(opponent, animTrack)
for animName, animId in pairs(Settings.SlapAnimations) do
if animTrack.Animation and animTrack.Animation.AnimationId == "rbxassetid://" .. animId then
print("Detected slap animation:", animName, "from:", opponent.Name)
handleSlapAnimation(opponent, animTrack)
break
end
end
end
local function onCharacterAdded(character, player)
local humanoid = character:WaitForChild("Humanoid")
humanoid.AnimationPlayed:Connect(function(animTrack)
onOpponentAnimationPlayed(player, animTrack)
end)
end
local function setupPlayer(player)
if player == Players.LocalPlayer then return end
if player.Character then
onCharacterAdded(player.Character, player)
end
player.CharacterAdded:Connect(function(character)
onCharacterAdded(character, player)
end)
-- Handle player leaving
player.CharacterRemoving:Connect(function()
if blockingPlayers[player.Name] then
blockingPlayers[player.Name] = nil
updateGUI()
print("Player left, removed from blocking list:", player.Name)
end
end)
end
-- Initialize Players
for _, player in ipairs(Players:GetPlayers()) do
setupPlayer(player)
end
Players.PlayerAdded:Connect(setupPlayer)
-- Key Binding
ContextActionService:BindAction("ToggleBlockingSystem", function(_, state)
if state == Enum.UserInputState.Begin then
toggleBlockingSystem()
end
end, false, Enum.KeyCode.R)
-- Initial GUI Update
updateGUI()
-- Display Instructions
print("Advanced Dynamic Slap Blocking System Initialized.")
print("Press 'R' to toggle the blocking system on and off.")
-- Main Loop for Continuous Updates
RunService.Heartbeat:Connect(function()
if isBlockingEnabled then
local closestPlayers = getClosestPlayers()
for _, playerInfo in ipairs(closestPlayers) do
local player = playerInfo.Player
if not blockingPlayers[player.Name] then
-- Optionally handle passive blocking or monitoring here
end
end
end
end)
-- Additional Enhancements:
-- 1. Dynamic Block Strength: Adjust block effectiveness based on opponent distance
local function calculateBlockEffectiveness(distance)
return math.clamp((Settings.BlockDistance - distance) / Settings.BlockDistance, 0.5, 1)
end
-- 2. Logging Block Events (Optional: Useful for debugging or analytics)
local function logBlockEvent(playerName, blocked)
local logMessage = blocked and ("Blocked a slap from " .. playerName) or ("Failed to block a slap from " .. playerName)
-- Implement logging mechanism here, e.g., send to a remote logging service
print(logMessage)
end
-- 3. Rate Limiting for Notifications to Prevent Spam
local lastNotificationTime = 0
local NotificationCooldown = 0.5 -- seconds
local function showRateLimitedNotification(message, isError)
local currentTime = getCurrentTime()
if (currentTime - lastNotificationTime) >= NotificationCooldown then
showNotification(message, isError)
lastNotificationTime = currentTime
end
end
-- Modify existing notification calls to use rate-limited version
-- Example:
-- showNotification("Blocked a slap from " .. opponent.Name, false)
-- becomes
-- showRateLimitedNotification("Blocked a slap from " .. opponent.Name, false)
-- Update handleSlapAnimation to use rate-limited notifications
local function handleSlapAnimation(opponent, animTrack)
if not isBlockingEnabled then return end
local localPlayer = Players.LocalPlayer
local character = localPlayer.Character
if not character or not character:FindFirstChild("HumanoidRootPart") then return end
local opponentRoot = opponent.Character:FindFirstChild("HumanoidRootPart")
if not opponentRoot then return end
local distance = (character.HumanoidRootPart.Position - opponentRoot.Position).Magnitude
if distance > Settings.BlockDistance then return end
local currentTime = getCurrentTime()
local opponentInfo = blockingPlayers[opponent.Name]
if opponentInfo then
if (currentTime - opponentInfo.LastBlockTime) < Settings.Cooldown then
print(string.format("Blocked recently by %s. Cooldown remaining: %.2f seconds", opponent.Name, Settings.Cooldown - (currentTime - opponentInfo.LastBlockTime)))
return
end
end
local dynamicReactionTime = Settings.ReactionTimeThreshold * (Settings.BlockDistance / math.max(distance,1))
dynamicReactionTime = math.clamp(dynamicReactionTime, 0.05, Settings.ReactionTimeThreshold)
local shouldBlock = false
local reactiveAnims = {"Slap", "RightSwing", "LeftSwing", "OverheadSwing", "DoubleSlap"}
for _, animName in ipairs(reactiveAnims) do
if animTrack.Animation.AnimationId == "rbxassetid://" .. Settings.SlapAnimations[animName] then
shouldBlock = true
break
end
end
if shouldBlock then
-- Initialize or update opponent's block info
blockingPlayers[opponent.Name] = {
LastBlockTime = currentTime,
BlockStartTime = currentTime
}
BlockRemote:FireServer(opponent)
blockSound:Play()
showRateLimitedNotification("Blocked a slap from " .. opponent.Name, false)
logBlockEvent(opponent.Name, true)
print("Blocking initiated against:", opponent.Name)
updateGUI()
task.delay(Settings.BlockDuration, function()
UnblockRemote:FireServer(opponent)
blockingPlayers[opponent.Name] = nil
print("Blocking ended for:", opponent.Name)
updateGUI()
end)
if Settings.AutoCounterEnabled and distance <= Settings.AutoSlapDistance then
task.delay(dynamicReactionTime, function()
VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.E, false, game)
task.wait(0.1)
VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.E, false, game)
counterSound:Play()
showRateLimitedNotification("Automatic counter-slap performed against " .. opponent.Name, false)
logBlockEvent(opponent.Name, true)
print("Automatic counter-slap performed against:", opponent.Name)
end)
end
end
end
Detailed Enhancements Explanation
-
Per-Player Cooldowns:
- Implementation: The
blockingPlayers table now holds individual cooldown data for each opponent. This allows the system to manage blocks on a per-player basis without a global cooldown affecting all interactions.
-
Sound and Visual Effects:
- Sound Effects: Two new sound instances,
blockSound and counterSound, are added. These play when a block is initiated and when an automatic counter-slap is performed, respectively. Replace "rbxassetid://YourBlockSoundID" and "rbxassetid://YourCounterSoundID" with actual sound asset IDs.
- Visual Feedback: Enhanced the GUI to include a
notificationFrame that displays transient messages to the player, providing immediate feedback on actions like blocking and counter-slapping.
-
Enhanced GUI:
- Block Indicator: Now displays the number of active blocks, giving players a clear understanding of their current blocking status.
- Notification System: Snackbar-style notifications appear at the bottom of the screen to inform players about actions such as enabling/disabling the blocking system, successful blocks, and counter-slaps.
- Dynamic Positioning: Notifications smoothly slide in and out using TweenService, improving user experience.
-
Dynamic Block Strength:
- Function:
calculateBlockEffectiveness (currently a placeholder) computes the effectiveness of a block based on the opponent's distance. This can be expanded to influence gameplay mechanics, such as reducing damage or varying the visual effect of blocks.
-
Notification System:
- Notifications: Implemented using the
showNotification function, providing real-time feedback to the player. A rate limiter ensures notifications aren’t spammed, maintaining clarity.
- Error Handling: Notifications can indicate errors (e.g., failed blocks) with different colors to differentiate from regular messages.
-
Robust Error Handling:
- Player Disconnection: When a player leaves the game, their entry is removed from the
blockingPlayers table to prevent errors and ensure the GUI remains accurate.
Final Notes
- Customization: Replace placeholder sound IDs with actual assets to ensure auditory feedback functions correctly.
- Testing: Thoroughly test the script in various scenarios to validate the new features and ensure compatibility with existing game mechanics.
- Optimization: Monitor performance, especially if handling a large number of players, and optimize as necessary to maintain smooth gameplay.
These enhancements aim to create a more immersive and efficient anti-slap system, providing players with clear feedback and robust protections against unwanted interactions.