Hi so I’m trying to make a basic knockback system,
a player hits another player or NPC and the NPC gets knocked back.
This code below doesn’t give any error outputs but it’s not knocking any NPCs back.
I checked and they’re not anchored.
It’s detecting the player and the NPC as well so I’m not sure what is going on here.
Any help would be appreciated.
game.ReplicatedStorage.knockback.knockback.OnServerEvent:Connect(function(player)
for _, target in pairs(game.Workspace:GetDescendants()) do
if target:IsA("Humanoid") and target.Parent.Name ~= player.Name then
if (target.Parent.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude < 5 then
local targetRootPart = target.Parent.PrimaryPart
local playerRootPart = player.Character.PrimaryPart
local velocity = Instance.new("BodyVelocity", targetRootPart)
velocity.MaxForce = Vector3.new(100000,100000,10000)
velocity.P = 10000
local angle = ((targetRootPart.Position - playerRootPart.Position) * Vector3.new(10,0,10)).Unit * 50 + Vector3.new(0,25,0)
velocity.Velocity = angle
wait(0.1)
velocity:Destroy()
print(target.Parent.Name, "was touched")
end
end
end
end)
game.ReplicatedStorage.knockback.knockback.OnServerEvent:Connect(function(player)
for _, target in pairs(game.Workspace:GetDescendants()) do
if target:IsA("Humanoid") and target.Parent.Name ~= player.Name then
if (target.Parent.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude < 5 then
local targetRootPart = target.Parent.PrimaryPart
local playerRootPart = player.Character.PrimaryPart
local velocity = Instance.new("BodyVelocity")
velocity.Parent = targetRootPart;
velocity.MaxForce = Vector3.new(100000,100000,10000)
velocity.P = 10000
local angle = ((targetRootPart.Position - playerRootPart.Position) * Vector3.new(10,0,10)).Unit * 50 + Vector3.new(0,25,0)
velocity.Velocity = angle
wait(0.1)
velocity:Destroy()
print(target.Parent.Name, "was touched")
end
end
end
end)
Maybe you could try parenting the BodyVelocity after you setup all the other properties? Especially the velocity. I usually do that for all instances, including my knockback system.
sorry for the long reply, I tried doing that but it still doesn’t manage to do anything. Kind of odd, I’m not really sure what’s 100% the issue since there’s literally no error output, everything runs it just seems that it doesn’t make the humanoid get knocked back.
okay so I tested it out and it actually works when I published the game and played it with a friend. Maybe it seems that it doesn’t work in the studio for me (maybe because of something I did but I’m not sure) so I’ll keep this for now. Thank you so much.