I made a script that makes a humanoid wander around randomly. At first, it would constantly run into walls, so I made a Ray that moves the humanoid to the center of the walled in area when it touches a wall. It works as intended, except for when it will randomly spin around in circles after hitting the wall instead of heading to the intended part. Usually, the script cannot break out of this, as the ray will just hit the wall again and cause it to spin once more. This doesn't happen every time it hits a wall, only after the first few times or later (It's pretty random). Here's the code:
``` local wanderTarget local wanderAngle local wanderConeSize = 6 local maxWanderAngle = 0.75 local Hit = nil
function getWanderTarget() math.random(tick()) wanderAngle = (math.random() - 0.5) * maxWanderAngle local rotatedLookVector = CFrame.Angles(0, wanderAngle, 0) * script.Parent.Torso.CFrame.lookVector return (script.Parent.Torso.Position + wanderConeSize * rotatedLookVector) end
while Hit == nil do
local orient = script.Parent.Torso.CFrame.LookVector * 8 local ray = Ray.new(script.Parent.Torso.Position, orient ) local Part, Position = game.Workspace:FindPartOnRay(ray, script.Parent)
--[[ local beam = Instance.new("Part", workspace) beam.BrickColor = BrickColor.new("Bright red") beam.FormFactor = "Custom" beam.Material = "Neon" beam.Transparency = 0.25 beam.Anchored = true beam.Locked = true beam.CanCollide = false local distance = (script.Parent.Torso.CFrame.p - Position).magnitude beam.Size = Vector3.new(0.3, 0.3, distance) --beam.CFrame = CFrame.new(script.Parent.Torso.CFrame.p, Position) * CFrame.new(0, 0, -distance / -3) beam.Position = script.Parent.Torso.Position beam.Orientation = script.Parent.Torso.Orientation game:GetService("Debris"):AddItem(beam, 0.001) --]]
if Hit == nil and script.Parent.Humanoid then wanderTarget = getWanderTarget() script.Parent.Humanoid:MoveTo(wanderTarget, script.Parent.Torso) wait(0.5) end
if Part then wait() print("Moving") script.Parent.Humanoid:MoveTo(game.Workspace.Center.Position) wait(1) Part = nil end end