I fire to the server, servers does the damage there + sets network owner to player who hit the mob. Idea is on the players 3rd swing, it’d be a crit and knock the mob back, however, atm it just gets flung around at random
HitMob:FireServer(Mob, self.SwingIndex)
local Crit = self.SwingIndex == 3
if Crit then -- Knockback
print("CURRENT POSITION", Mob.PrimaryPart.CFrame.LookVector)
local Direction = Mob.PrimaryPart.CFrame.LookVector * -100000
Mob.PrimaryPart:ApplyImpulse(Direction)
end
You can try making the Direction variable the direction the mob is relative to the player. You will have to get the character of the player who hit it though.
local Multiplier = 10 -- you'll need to edit this
local playerPos = PlayerCharacter:GetPivot().Position
local mobPos = Mob:GetPivot().Position
-- relevant code:
local direction = (mobPos - playerPos).Unit
local relativeY = if math.sign(mobPos.Y - playerPos.Y) >= 0 then 1 else -1 -- whether the knockback effect is down or up
direction = Vector3.new(direction.X, relativeY, direction.Z) -- the force applied in the knockback effect along the y-axis
Mob.PrimaryPart:ApplyImpulse(Direction * (Mob.PrimaryPart.AssemblyMass * math.sqrt(workspace.Gravity)) * Multiplier)
Alright, my bad. Looking at my previous code, I was forgetting to divide the relativeY value by the direction vectors magnitude. However, I realized that you don’t even need a defined y value unless you want greater control.
Here’s an updated function that should work, as I’ve actually tested it.
local Player: Model = workspace:WaitForChild("Character")
local Mob: Model = workspace:WaitForChild("Dummy")
local function RepelFrom(position: Vector3, mobs: {Model}, force: number)
force = force or 10
local gravityForce: number = math.sqrt(workspace.Gravity)
local sign = math.sign
for _,mob: Model in pairs(mobs) do
local mobPart: BasePart = mob.PrimaryPart or mob:FindFirstChildOfClass("BasePart")
mobPart:ApplyImpulse((mob:GetPivot().Position - position).Unit * (mobPart.AssemblyMass * gravityForce) * force)
end
end
RepelFrom(Player:GetPivot().Position, {Mob}, 7)