Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local Players = game:GetService("Players")
- local Debris = game:GetService("Debris")
- local Workspace = game:GetService("Workspace")
- local tool = script.Parent
- local punchEvent = tool:WaitForChild("PunchEvent")
- --------------------------------------------------
- -- НАСТРОЙКИ ОРУЖИЯ
- --------------------------------------------------
- local DAMAGE = 6
- local COOLDOWN = 0.65
- -- Задержка попадания после начала анимации
- local HIT_DELAY = 0.15
- -- Продолжительность проверки попадания
- local HIT_WINDOW = 0.10
- -- Размер области удара
- local HITBOX_SIZE = Vector3.new(4.5, 4.5, 4.5)
- -- Положение области перед игроком
- local HITBOX_OFFSET = CFrame.new(0, 0, -2.5)
- -- Сила отбрасывания
- local PUSH_SPEED = 28
- local UPWARD_SPEED = 8
- -- Длительность Ragdoll
- local RAGDOLL_DURATION = 2
- local lastPunch = {}
- -- Состояния упавших персонажей
- local ragdolls = setmetatable({}, {__mode = "k"})
- --------------------------------------------------
- -- МЕТКА УБИЙЦЫ ДЛЯ ТАБЛИЦЫ ЛИДЕРОВ
- --------------------------------------------------
- local function tagCreator(humanoid, player)
- local oldTag = humanoid:FindFirstChild("creator")
- if oldTag then
- oldTag:Destroy()
- end
- local tag = Instance.new("ObjectValue")
- tag.Name = "creator"
- tag.Value = player
- tag.Parent = humanoid
- Debris:AddItem(tag, 5)
- end
- --------------------------------------------------
- -- RAGDOLL
- --------------------------------------------------
- local function startRagdoll(character, humanoid)
- local state = ragdolls[humanoid]
- -- Если персонаж уже падает,
- -- не создаём соединения повторно
- if not state then
- state = {
- version = 0,
- attachments = {},
- motors = {},
- animationConstraints = {},
- oldAutoRotate = humanoid.AutoRotate,
- oldPlatformStand = humanoid.PlatformStand,
- oldRequiresNeck = humanoid.RequiresNeck,
- oldBreakJointsOnDeath = humanoid.BreakJointsOnDeath
- }
- ragdolls[humanoid] = state
- -- Папка для физических соединений
- local folder = Instance.new("Folder")
- folder.Name = "RagdollConstraints"
- folder.Parent = character
- state.folder = folder
- -- Сохраняем шею от случайного отключения
- humanoid.RequiresNeck = false
- -- Сохраняем соединения даже при смерти
- humanoid.BreakJointsOnDeath = false
- -- Отключаем управление и поворот
- humanoid.AutoRotate = false
- humanoid.PlatformStand = true
- humanoid:ChangeState(
- Enum.HumanoidStateType.PlatformStanding
- )
- -- Передаём управление физикой серверу
- local root =
- character:FindFirstChild("HumanoidRootPart")
- or character:FindFirstChild("Torso")
- or character.PrimaryPart
- if root and not root.Anchored then
- pcall(function()
- root:SetNetworkOwner(nil)
- end)
- end
- -- Останавливаем текущие анимации,
- -- чтобы они не мешали падению
- local animator = humanoid:FindFirstChildOfClass("Animator")
- if animator then
- for _, track in ipairs(animator:GetPlayingAnimationTracks()) do
- track:Stop(0.05)
- end
- end
- --------------------------------------------------
- -- НОВЫЕ СОЕДИНЕНИЯ ANIMATIONCONSTRAINT
- --------------------------------------------------
- for _, joint in ipairs(character:GetDescendants()) do
- if joint:IsA("AnimationConstraint") then
- local attachment0 = joint.Attachment0
- local attachment1 = joint.Attachment1
- local part0 = attachment0 and attachment0.Parent
- local part1 = attachment1 and attachment1.Parent
- if attachment0 and attachment1
- and part0 and part1
- and part0:IsA("BasePart")
- and part1:IsA("BasePart")
- and part0.Name ~= "HumanoidRootPart"
- and part1.Name ~= "HumanoidRootPart" then
- table.insert(
- state.animationConstraints,
- {
- joint = joint,
- oldValue = joint.IsKinematic
- }
- )
- -- Переводим соединение в физический режим
- joint.IsKinematic = false
- end
- end
- end
- --------------------------------------------------
- -- СТАРЫЕ СОЕДИНЕНИЯ MOTOR6D
- --------------------------------------------------
- for _, joint in ipairs(character:GetDescendants()) do
- if joint:IsA("Motor6D")
- and joint.Part0
- and joint.Part1 then
- -- Не отключаем соединение с корнем персонажа
- local connectedToRoot =
- joint.Part0.Name == "HumanoidRootPart"
- or joint.Part1.Name == "HumanoidRootPart"
- if not connectedToRoot then
- -- Создаём точки соединения
- local attachment0 = Instance.new("Attachment")
- attachment0.CFrame = joint.C0
- attachment0.Parent = joint.Part0
- local attachment1 = Instance.new("Attachment")
- attachment1.CFrame = joint.C1
- attachment1.Parent = joint.Part1
- -- Создаём физический сустав
- local socket = Instance.new("BallSocketConstraint")
- socket.Attachment0 = attachment0
- socket.Attachment1 = attachment1
- socket.LimitsEnabled = true
- if joint.Name == "Neck" then
- socket.UpperAngle = 25
- else
- socket.UpperAngle = 50
- end
- socket.TwistLimitsEnabled = true
- socket.TwistLowerAngle = -35
- socket.TwistUpperAngle = 35
- socket.Parent = folder
- table.insert(state.attachments, attachment0)
- table.insert(state.attachments, attachment1)
- -- Запоминаем исходное состояние Motor6D
- table.insert(
- state.motors,
- {
- joint = joint,
- oldValue = joint.Enabled
- }
- )
- -- Отключаем обычное движение сустава
- joint.Enabled = false
- end
- end
- end
- -- Если персонаж погиб, оставляем его в ragdoll
- humanoid.Died:Connect(function()
- if ragdolls[humanoid] == state then
- ragdolls[humanoid] = nil
- end
- end)
- end
- --------------------------------------------------
- -- ОБНОВЛЯЕМ ВРЕМЯ ПАДЕНИЯ
- --------------------------------------------------
- state.version += 1
- local currentVersion = state.version
- task.delay(RAGDOLL_DURATION, function()
- -- Проверяем, не продлён ли Ragdoll новым ударом
- if ragdolls[humanoid] ~= state then
- return
- end
- if state.version ~= currentVersion then
- return
- end
- -- Погибших персонажей не поднимаем
- if not humanoid.Parent or humanoid.Health <= 0 then
- ragdolls[humanoid] = nil
- return
- end
- --------------------------------------------------
- -- ВОССТАНАВЛИВАЕМ СОЕДИНЕНИЯ
- --------------------------------------------------
- if state.folder and state.folder.Parent then
- state.folder:Destroy()
- end
- -- Удаляем временные Attachment
- for _, attachment in ipairs(state.attachments) do
- if attachment.Parent then
- attachment:Destroy()
- end
- end
- -- Восстанавливаем Motor6D
- for _, data in ipairs(state.motors) do
- if data.joint.Parent then
- data.joint.Enabled = data.oldValue
- end
- end
- -- Восстанавливаем AnimationConstraint
- for _, data in ipairs(state.animationConstraints) do
- if data.joint.Parent then
- data.joint.IsKinematic = data.oldValue
- end
- end
- --------------------------------------------------
- -- ВОЗВРАЩАЕМ УПРАВЛЕНИЕ
- --------------------------------------------------
- humanoid.RequiresNeck = state.oldRequiresNeck
- humanoid.BreakJointsOnDeath = state.oldBreakJointsOnDeath
- humanoid.AutoRotate = state.oldAutoRotate
- humanoid.PlatformStand = state.oldPlatformStand
- if not state.oldPlatformStand then
- humanoid:ChangeState(
- Enum.HumanoidStateType.GettingUp
- )
- end
- -- Возвращаем автоматическое управление физикой
- local root =
- humanoid.Parent:FindFirstChild("HumanoidRootPart")
- or humanoid.Parent:FindFirstChild("Torso")
- if root and not root.Anchored then
- pcall(function()
- root:SetNetworkOwnershipAuto()
- end)
- end
- ragdolls[humanoid] = nil
- end)
- end
- --------------------------------------------------
- -- ОТБРАСЫВАНИЕ ПРОТИВНИКА
- --------------------------------------------------
- local function knockback(attackerRoot, targetRoot, targetModel, targetHumanoid)
- if not targetRoot or targetRoot.Anchored then
- return
- end
- -- Сначала переводим противника в Ragdoll
- startRagdoll(targetModel, targetHumanoid)
- -- Определяем направление отбрасывания
- local direction = targetRoot.Position - attackerRoot.Position
- -- Убираем вертикальное направление
- direction = Vector3.new(direction.X, 0, direction.Z)
- if direction.Magnitude < 0.001 then
- local look = attackerRoot.CFrame.LookVector
- direction = Vector3.new(look.X, 0, look.Z)
- end
- if direction.Magnitude < 0.001 then
- return
- end
- direction = direction.Unit
- -- Создаём физический импульс
- local mass = targetRoot.AssemblyMass
- if mass <= 0 or mass >= math.huge then
- return
- end
- local impulse = (
- direction * PUSH_SPEED
- + Vector3.new(0, UPWARD_SPEED, 0)
- ) * mass
- targetRoot:ApplyImpulse(impulse)
- end
- --------------------------------------------------
- -- ПОИСК HUMANOID
- --------------------------------------------------
- local function findHumanoid(part)
- local current = part
- while current and current ~= Workspace do
- if current:IsA("Model") then
- local humanoid =
- current:FindFirstChildOfClass("Humanoid")
- if humanoid then
- return current, humanoid
- end
- end
- current = current.Parent
- end
- return nil, nil
- end
- --------------------------------------------------
- -- ПОИСК И АТАКА ЦЕЛЕЙ
- --------------------------------------------------
- local function performHit(player, character, attackerHumanoid, attackerRoot)
- -- Исключаем самого атакующего
- local overlapParams = OverlapParams.new()
- overlapParams.FilterType = Enum.RaycastFilterType.Exclude
- overlapParams.FilterDescendantsInstances = {character}
- overlapParams.MaxParts = 100
- -- Одна цель не может получить повторный урон
- -- от одного и того же удара
- local alreadyHit = {}
- local finishTime = os.clock() + HIT_WINDOW
- repeat
- if tool.Parent ~= character then
- break
- end
- local hitboxCFrame =
- attackerRoot.CFrame * HITBOX_OFFSET
- local parts = Workspace:GetPartBoundsInBox(
- hitboxCFrame,
- HITBOX_SIZE,
- overlapParams
- )
- for _, part in ipairs(parts) do
- local targetModel, targetHumanoid = findHumanoid(part)
- if targetHumanoid
- and targetHumanoid ~= attackerHumanoid
- and targetHumanoid.Health > 0
- and not alreadyHit[targetHumanoid] then
- -- Не бьём персонажей под защитой ForceField
- if not targetModel:FindFirstChildOfClass("ForceField") then
- alreadyHit[targetHumanoid] = true
- -- Ищем корневую часть противника
- local targetRoot =
- targetModel:FindFirstChild("HumanoidRootPart")
- or targetModel:FindFirstChild("Torso")
- or targetModel.PrimaryPart
- -- Записываем убийцу
- tagCreator(targetHumanoid, player)
- -- Удар и Ragdoll
- if targetRoot and not targetRoot.Anchored then
- knockback(
- attackerRoot,
- targetRoot,
- targetModel,
- targetHumanoid
- )
- end
- -- Наносим урон
- targetHumanoid:TakeDamage(DAMAGE)
- print(
- player.Name ..
- " ударил " ..
- targetModel.Name ..
- " | Урон: " ..
- DAMAGE
- )
- end
- end
- end
- task.wait(0.04)
- until os.clock() >= finishTime
- end
- --------------------------------------------------
- -- ПОЛУЧЕНИЕ ЗАПРОСА НА УДАР
- --------------------------------------------------
- punchEvent.OnServerEvent:Connect(function(player)
- local character = player.Character
- -- Проверяем, что оружие действительно экипировано
- if not character or tool.Parent ~= character then
- return
- end
- local humanoid = character:FindFirstChildOfClass("Humanoid")
- local root = character:FindFirstChild("HumanoidRootPart")
- if not humanoid or humanoid.Health <= 0 or not root then
- return
- end
- -- Нельзя атаковать, пока сам игрок лежит
- if humanoid.PlatformStand then
- return
- end
- -- Проверка перезарядки на сервере
- local now = os.clock()
- if lastPunch[player]
- and now - lastPunch[player] < COOLDOWN then
- return
- end
- lastPunch[player] = now
- -- Ждём момент удара в анимации
- task.delay(HIT_DELAY, function()
- -- Повторно проверяем состояние игрока
- if player.Character ~= character
- or tool.Parent ~= character
- or humanoid.Health <= 0 then
- return
- end
- if not root.Parent then
- return
- end
- performHit(
- player,
- character,
- humanoid,
- root
- )
- end)
- end)
- --------------------------------------------------
- -- ОЧИСТКА
- --------------------------------------------------
- Players.PlayerRemoving:Connect(function(player)
- lastPunch[player] = nil
- end)
Advertisement
Add Comment
Please, Sign In to add comment