Certainly! Here's an enhanced version of your anti-slap Roblox script with several improvements to optimize performance, maintainability, and functionality:
- Cooldown Implementation: Prevents the script from blocking too frequently, avoiding potential spam or unwanted behavior.
- Performance Optimization: Uses squared distances to avoid unnecessary square root calculations, enhancing performance.
- Exclusion of Local Player: Ensures the script doesn't respond to the local player's own actions.
- Robust Event Handling: Manages connections efficiently and updates references when characters respawn.
- Configuration Management: Centralizes settings for easier adjustments and better readability.
- Enhanced Readability: Adds comprehensive comments and organizes the code for better understanding and maintenance.
Below is the improved script with detailed comments explaining each part:
-- Enhanced Anti-Slap Roblox Script
--[[
This script automatically blocks slap animations from opponents and can counter-slap
if configured. It includes cooldowns to prevent excessive blocking and optimizes
performance by using squared distance comparisons.
]]
-- Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local VirtualInputManager = game:GetService("VirtualInputManager")
-- Remote Events for Blocking Mechanism
local LightsaberRemotes = ReplicatedStorage:WaitForChild("LightsaberRemotes")
local BlockRemote = LightsaberRemotes:WaitForChild("Block")
local UnblockRemote = LightsaberRemotes:WaitForChild("Unblock")
-- Configuration Settings
local CONFIG = {
BlockDistance = 15, -- Maximum distance to attempt a block (studs)
AutoCounterEnabled = true, -- Enable automatic counter-slapping
AutoSlapDistance = 10, -- Maximum distance to auto counter slap (studs)
BlockCooldown = 1, -- Cooldown period between blocks (seconds)
CounterKey = Enum.KeyCode.E, -- Key to press for counter action
SlapAnimationIds = { -- Table of animation IDs considered as 'slaps'
["Slap"] = 12625891544,
["SlappedLegs"] = 12671715182,
["SlappedArms"] = 12625896358
}
}
-- Cache the Local Player
local localPlayer = Players.LocalPlayer
assert(localPlayer, "LocalPlayer not found") -- Ensure LocalPlayer is available
-- Initialize Character References
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
-- Variable to track the last block time for cooldown
local lastBlockTime = 0
-- Helper Function: Calculate Squared Distance Between Two Positions
local function getDistanceSq(position1, position2)
local diff = position1 - position2
return diff.X * diff.X + diff.Y * diff.Y + diff.Z * diff.Z
end
-- Function: Handle a Slap Animation Played by an Opponent
local function handleSlapAnimation(opponent, animTrack)
local currentTime = tick()
-- Check if cooldown has passed
if currentTime - lastBlockTime < CONFIG.BlockCooldown then
return -- Still in cooldown; do not block
end
-- Update the last block time
lastBlockTime = currentTime
-- Retrieve Opponent's HumanoidRootPart
local opponentCharacter = opponent.Character
if not opponentCharacter then return end
local opponentRootPart = opponentCharacter:FindFirstChild("HumanoidRootPart")
if not opponentRootPart then return end
-- Calculate Squared Distance
local distanceSq = getDistanceSq(humanoidRootPart.Position, opponentRootPart.Position)
local blockDistanceSq = CONFIG.BlockDistance * CONFIG.BlockDistance
-- Check if Opponent is Within Block Distance
if distanceSq <= blockDistanceSq then
-- Fire Block Event to Server
BlockRemote:FireServer()
-- Schedule Unblock After Animation Duration
coroutine.wrap(function()
-- Clamp wait time to prevent excessive delays
local waitTime = math.clamp(animTrack.Length, 0.1, 5)
task.wait(waitTime)
UnblockRemote:FireServer()
end)()
-- Handle Auto Counter Slap if Enabled and Within Auto Slap Distance
if CONFIG.AutoCounterEnabled then
local autoSlapDistanceSq = CONFIG.AutoSlapDistance * CONFIG.AutoSlapDistance
if distanceSq <= autoSlapDistanceSq then
-- Simulate Key Press for Counter Action
VirtualInputManager:SendKeyEvent(true, CONFIG.CounterKey, false, game)
task.wait(0.05) -- Short delay to mimic a real key press
VirtualInputManager:SendKeyEvent(false, CONFIG.CounterKey, false, game)
end
end
end
end
-- Function: Monitor and Respond to Animation Events
local function onAnimationPlayed(opponentPlayer, animTrack)
local animId = animTrack.Animation.AnimationId
for _, id in pairs(CONFIG.SlapAnimationIds) do
if animId == "rbxassetid://" .. tostring(id) then
handleSlapAnimation(opponentPlayer, animTrack)
break -- No need to check other IDs once matched
end
end
end
-- Function: Connect to a Player's Animation Events
local function connectAnimationMonitoring(player)
if player == localPlayer then return end -- Exclude Local Player
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
humanoid.AnimationPlayed:Connect(function(animTrack)
onAnimationPlayed(player, animTrack)
end)
end
-- Connect to Existing Character or Wait for Character to Load
if player.Character then
onCharacterAdded(player.Character)
end
-- Connect to Future Character Additions
player.CharacterAdded:Connect(onCharacterAdded)
end
-- Initial Setup: Connect to All Existing Players
for _, player in ipairs(Players:GetPlayers()) do
connectAnimationMonitoring(player)
end
-- Listen for New Players Joining the Game
Players.PlayerAdded:Connect(function(player)
connectAnimationMonitoring(player)
end)
-- Update References When Local Player's Character Respawns
localPlayer.CharacterAdded:Connect(function(char)
character = char
humanoidRootPart = char:WaitForChild("HumanoidRootPart")
end)
Key Enhancements Explained:
-
Cooldown Mechanism:
- Purpose: Prevents the script from attempting to block too frequently, which can cause unwanted behavior or server strain.
- Implementation: Uses
tick() to track the time and ensures that a new block action only occurs if the cooldown period has elapsed.
-
Performance Optimization with Squared Distance:
- Purpose: Reduces computational overhead by avoiding the expensive square root operation involved in calculating actual distances.
- Implementation: Compares squared distances (
distanceSq) with squared threshold values (blockDistanceSq and autoSlapDistanceSq).
-
Exclusion of Local Player:
- Purpose: Ensures that the script doesn't react to the local player's own animations, preventing self-interference.
- Implementation: Checks if the opponent player is not the
localPlayer before processing.
-
Robust Event Handling:
- Purpose: Ensures that animation events are correctly monitored and responded to, even when players respawn.
- Implementation: Connects to both existing and newly added players, and updates character references when the local player respawns.
-
Configuration Management:
- Purpose: Centralizes all configurable settings, making it easier to adjust parameters like distances, cooldowns, and key bindings.
- Implementation: Utilizes a
CONFIG table to store all settings, enhancing readability and maintainability.
-
Enhanced Readability and Maintainability:
- Purpose: Makes the script easier to understand, modify, and debug.
- Implementation: Adds comprehensive comments, organizes code into logical sections, and follows consistent naming conventions.
-
Error Handling and Assertions:
- Purpose: Ensures that essential components like
LocalPlayer are available, preventing runtime errors.
- Implementation: Uses to check the existence of .
Additional Recommendations:
-
Visual or Audio Feedback: Consider adding visual indicators (like UI elements) or sound effects when a block or counter-slap occurs. This can enhance user experience and provide clear feedback.
-
Dynamic Configuration: Implement a GUI panel that allows players to adjust settings in real-time without modifying the script. This provides flexibility and user control.
-
Logging and Debugging: Incorporate logging mechanisms to track when blocks and counter-slaps occur. This can be invaluable for debugging and understanding player interactions.
-
Security Considerations: Ensure that the remote events (Block and Unblock) are securely handled on the server-side to prevent exploitation or unauthorized actions.
By implementing these enhancements, the anti-slap script becomes more efficient, reliable, and user-friendly, providing a better experience for players while maintaining optimal performance.