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: