So I'm scripting an NPC which moves randomly, and it also uses raycasting to detect any objects in front of it. However, whenever it detects a wall in front of it, it doesn't rotate properly. Sometimes it will rotate, but other times it just runs into the wall instead.

This is the script:

local npc = script.Parent
local npcHumanoid = npc.Humanoid
local npcTorso = npc.HumanoidRootPart
local walked = false

while wait(1) do
	
	
	
	local detectWall = Ray.new(npcTorso.Position, npcTorso.CFrame.LookVector * 50)
	local obj, position = workspace:FindPartOnRayWithIgnoreList(detectWall, {npc})
	
	wait(2)
	if obj then
		
		npcHumanoid:MoveTo(npcTorso.Position + Vector3.new(math.rad(180), 0, 0))
		
		print("lll")
	
	elseif not obj then
		
		print("lol")
		npcHumanoid:MoveTo(npcTorso.Position + Vector3.new(math.random(-30, 30), 0, math.random(-30, 30)))
		npcHumanoid.MoveToFinished:Wait()
		
		
			
	end
end

I couldn't find anything on google which could answer my problem, so if anybody could help, it would be appreciated