How can I make script that pushes two players away when they are about to hit each other?

I have 2 players in a Linear setting where they face each other in a straight line and can only move forwards and backwards with custom buttons I’ve made. How can I prevent them from hitting each other because if they do they go above one another and its a mess. I use BodyVelocity for the movements because even though its deprecated it is more useful that LinearForce which I’ve tried using to push them back when about to meet but it doesnt really work

local function Distancer(plr, db)
	local char
	if plr.Character then
		db = false
		char = plr.Character
		local veloc = Instance.new("LinearVelocity", char)
		veloc.Attachment0 = char.HumanoidRootPart.RootRigAttachment
		veloc.VectorVelocity = (char:GetPivot().LookVector*(-10))*10
		veloc.MaxForce = 5000
		veloc.RelativeTo = Enum.ActuatorRelativeTo.World
		coroutine.wrap(function()
			task.wait(0.2)
			veloc:Destroy()
			db = true
		end)()
	end
end


local radius = 7
local db = false

while task.wait(.1) do
	local BluePos = BluePlayer.Character.HumanoidRootPart.Position
	local RedPos = RedPlayer.Character.HumanoidRootPart.Position
	local currentRadius = BluePlayer:DistanceFromCharacter(RedPos)
	if not db and radius > 0 and currentRadius <= radius then
		Distancer(BluePlayer, db)
		Distancer(RedPlayer, db)
	end
end

Use a raycast and cast it from the HumanoidRootPart.
Let’s say the variable result is the result of the raycast.
You should then get the result.Distance. With this you know how far they are standing away. Launch the same raycast every tenth of a second or so and as soon as the distance is 5 studs or less push them away from another.

Edit: Be aware that it is require that no other physical object stands inbetween those two players.
If so you will have to check if the result.Instance.Parent has a Humanoid.
Now when doing this you also have to be aware that no other entity stands in between the first player and the second player.
I’m not sure if your making some sort of fighting game, but if so your probably have both players names and can check the result.Instance.Parent for it’s name (or use :GetPlayerFromCharacter) to see if it’s the object you’re seeking.

2 Likes