How to create collision sliding

I want to make it so when the part collides into an obstacle, it slides around the obstacle. I tried lots of ways trying to get this to work and the closest I could get was good but it sometimes doesn’t go in the right sliding direction.

Code:

local RunService = game:GetService("RunService")

local part = script.Parent
local targetPart = workspace:WaitForChild("TargetPart")

local speed = 10
local collisionRadius = 5

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {workspace.Obstacles}
raycastParams.FilterType = Enum.RaycastFilterType.Include

local function CollideAndSlide(position, targetPos, direction, velocity, delta)
	local raycast = workspace:Spherecast(position, collisionRadius, velocity, raycastParams)

	local newPosition = position + velocity

	if raycast then
		local instance = raycast.Instance
		local normal = raycast.Normal

		local newDirection = (position - instance.Position).Unit * Vector3.new(1, 0, 1)

		local dot = math.clamp(targetPos:Dot(velocity), -1, 1)
		local cross = Vector3.new(0, 1, 0):Cross(normal.Unit) * dot

		newPosition = position + cross.Unit * collisionRadius * delta
	end

	return newPosition
end

RunService.Heartbeat:Connect(function(delta)
	local origin = part.Position
	local targetPos = targetPart.Position
	local direction = (targetPos - origin).Unit * Vector3.new(1, 0, 1)

	local velocity = direction * speed * delta
	local newPosition = CollideAndSlide(origin, targetPos, direction, velocity, delta)

	part.CFrame = CFrame.lookAlong(newPosition, direction)
end)

Problems may be:

What it should be:

1 Like

Your X and Z values are positive so your part can only move to its right with respect to its CFrame

To fix this you need to figure out if its quicker to go around the right or left, and if its the left then set the values to be negative. Good luck

1 Like

I don’t really know what you mean. I think you are saying that when I multiply the direction by Vector3.new(1, 0, 1), it turns positive?

Yes. It’s like a graph in math class. Incase its new to you

1 Like

Im pretty sure multiplying a negative to a positive keeps it a negative? 1*-1=-1

or are you saying multiplying a negative by a negative turns into a positive?