How can I make a ball roll away from a player nearby?

Today, I wanted to make a ball detect a player nearby and run away.
There is a BodyForce inside of the ball to make it move.
The issue is that the formula doesn’t work so well.
I tried searching for some solutions but there isn’t any perfect results for this issue.

Formula:

Part.BodyForce.Force = (players[n].Character.HumanoidRootPart.Position)*-1

Function:

local function FindTarget()
	local MaxDistance = 20
	local BestTarget = nil
	local players = game:GetService("Players"):GetPlayers()

	for n = 1,#players do
		if players[n].Character ~= nil and players[n].Character.HumanoidRootPart then
			local dist = (players[n].Character.HumanoidRootPart.Position - Part.Position).magnitude
			local Humanoid = players[n].Character:FindFirstChild("Humanoid")
			if dist and dist < MaxDistance and Humanoid then
				Part.BodyForce.Force = (players[n].Character.HumanoidRootPart.Position)*-1
			else
				Part.BodyForce.Force = Vector3.new(0,0,0)
			end
			break
		end
	end
end

Any help and feedback is appreciated!

Maybe you could make an invisible sphere around the player that only the ball can collide with.

I appreciate your feedback but, the goal is I want to make sure the ball doesn’t get caught so easily by making it roll to the opposite direction from the player.

Try

local diff = Part.Position - players[n].Character.HumanoidRootPart.Position
local dist = diff.Magnitude
Part.BodyForce.Force = 1000 * diff.Unit / dist

The 1000 is a multiplier. The force will be higher the closer you are (because of the division).

1 Like