How to have mobs get knocked back when hit

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

ill link a post with a similar issue, and you can adjust the code to work with the monsters rather than the client

Doesn’t really apply a nice knockback effect :confused: Gives off a more slide back effect

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)

The mob doesn’t seem to move :confused:

Sorry, I realized that the code wasn’t complete and edited it. Also, try modifying the Multiplier value.

You can’t assign a value to direction.Y. It’s read only

1 Like

Alright, fixed it. Is it still not working?

Sorry for late response.

Mobs now just to kinda jump in the air a couple of studs, but no real knockback

have you edited the Multiplier value to something greater than 10?

Ye, changed it to 50. Mob just goes up, they might go back like 4-5 studs, but the mainly just get flung up in the air

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)