Pull based on distance

I have a move that pulls the enemy to the player using a .unit bodyvelocity, but when they are too close they get pulled back. How do I make it reliant on distance, if they are far away, they get pulled a bit, if they are too close, they don’t get pulled that much.
Here’s what’s handling the pull

			local Velocityyy = damagetable.PushBack
			local d = (hitchar.HumanoidRootPart.Position - char.HumanoidRootPart.Position).unit
			bv.velocity =  (d * Velocityyy) 
				bv.Parent = hitchar.Head
				local timee = damagetable.PushBackTime
				if timee == nil then
					timee = .2
				end
				Utilities.Debris(bv, timee)
				Utilities.Debris(FLIGN, timee)

It may be as simple as changing the d value to

local d = (hitchar.HumanoidRootPart.Position - char.HumanoidRootPart.Position).Magnitude
1 Like

If it worked you can mark the post as solved to show that the issue has been resolved. Glad I could help :slight_smile:

It is not pulling them at all, here’s what the velocity is.

					bv.Velocity = (hitchar.HumanoidRootPart.Position - char.HumanoidRootPart.Position).Magnitude * Velocityyy

This is what I was using before:

			local d = (hitchar.HumanoidRootPart.Position - char.HumanoidRootPart.Position).unit
			bv.velocity =  (d * Velocityyy) 

although it still pulls behind the player.
I do not want to tween the enemy’s cframe to the player, because I want it to pull a good amount, but pull only enough if they are too close.

This may sound terrible, but you could do magnitude checks every heartbeat, or alternatively use repeat until etc etc…

Here’s two examples:

local d = (hitchar.HumanoidRootPart.Position - char.HumanoidRootPart.Position).Unit

repeat bv.Velocity = (d * Velocityyy) until (hitchar.HumanoidRootPart.Position - 
char.HumanoidRootPart.Position).Magnitude < 5 --// This whole section is meant to be one line, mb.

bv.MaxForce = Vector3.new()
bv.Velocity = Vector3.new()

Or you could attempt to connect a RunService Heartbeat event, then check for magnitude every heartbeat and then disconnect it if the two characters are close enough.

local function GetVelocity(TargRoot,PlayerRoot,Velocity)
    local d = (TargRoot.Position - PlayerRoot).Unit
    return (d*Velocity)
end

local function CheckDistance(A,B)
    return (A-B).Magnitude
end

local Connection; Connection = RunService.Heartbeat:Connect(function()
    Pull()
    
    if CheckDistance(TargetRoot.Position,PlayerRoot.Position) < 5 then
         Connection:Disconnect()
         bv.MaxForce = Vector3.new()
         bv.Velocity = Vector3.new()
    end
end

Hopefully this helps, also please, don’t just copy and paste the code, it won’t work straight up, you have to do a tiny bit of learning and or apply some of it yourself. Good luck!

1 Like