I was making a shark. I did all the Pathfinding stuff, but when I made the stuff that actually MOVE the shark, I found something strange. The MeshPart in the shark just disappears, but the point folder stays there. I tried putting all my scripts etc. in a regular part. The results I got were strange. The BodyPosition just stayed at (0, 50, 0) even when I was really close to it, when it should've moved. Here's the whole script, to help you point me in the right direction. The script includes the pathfinding, point creation, and what should've moved the shark.

function FindNearestPlayer()
	local lowest = 450
	local nearestPlayer = script.Parent.NearestPlayer
	local allPlayers = game.Players:GetPlayers()
	for i, v in pairs(allPlayers) do
		if v and v.Character then
			local distance = v:DistanceFromCharacter(script.Parent.Position)
			if distance < lowest then
				lowest = distance
				nearestPlayer.Value = tostring(v)
			end
		end
	end
	return nearestPlayer.Value
end

local pathfindingService = game:GetService("PathfindingService")

function computePath()
	if script.Parent.NearestPlayer.Value ~= nil and script.Parent.NearestPlayer.Value ~= "" then
		local closestPlayerName = script.Parent.NearestPlayer
		local plr = game.Players:WaitForChild(closestPlayerName.Value)
		local char = plr.Character
		local start = script.Parent
		local finish = char.Torso
	
	--Calculates the path
		local path = pathfindingService:FindPathAsync(start.Position, finish.Position)
		local waypoints = path:GetWaypoints()
	
	--Create a part for each point.
		script.Parent.Parent.PointFolder:ClearAllChildren()
		for waypoints, point in pairs(waypoints) do
			local part = Instance.new("Part")
			part.Size = Vector3.new(1, 1, 1)
			part.Position = point.Position
			part.Parent = script.Parent.Parent.PointFolder
			part.Anchored = true
			part.Name = "Part" .. waypoints
			part.CanCollide = false
			part.Transparency = 1
		end

	end --if
end

--Now begins the dreaded part. The part that was supposed to move the shark.
local Shark = script.Parent
local allPoints = script.Parent.Parent.PointFolder:GetChildren()

local BP = script.Parent.BodyPosition
BP.MaxForce = Vector3.new(1,1,1)*math.huge
local BG = Instance.new("BodyGyro")
BG.MaxTorque = Vector3.new(1,1,1)*math.huge
BG.Parent = Shark

for _, Point in pairs(allPoints) do
	BP.Position = Shark.Position
	BG.CFrame = CFrame.new(Shark.Position, Point.Position)
	BP.ReachedTarget:Wait()
end

--This tries to find the nearest player as soon as possible.
while true do
	wait(1)
	FindNearestPlayer()
	if script.Parent.NearestPlayer.Value ~= nil then
		script.Parent.Parent.PointFolder:ClearAllChildren()
		computePath()
	end
end

Thanks in advance!

2 comments

0

I don't really have time to read through all your NPC AI stuff, but every time I've gotten weird stuff like this with AI and Pathfinding NPCs its almost always a logic error.

0

Oh, okay. Gonna experiment a lot with this thing.