How to improve this chase AI?

So I’m making a game that has a monster, who will lock onto the nearest player and chase them down. And all of it works until the monster has to jump over something. It sometimes jumps too early, and misses where it was aiming for, then proceeds to get stuck in a wall


local function followPlayer(target)
	local playerRoot = target:FindFirstChild("HumanoidRootPart")
	local playerHum = target:FindFirstChild("Humanoid")
	if playerRoot ~= nil and playerHum.Health > 0 then
		path = getPath(playerRoot)
		local waypoints = path:GetWaypoints()

		if path.Status == Enum.PathStatus.Success then
			local waypoint, index
			local jumpWaypoint

			for i, point in pairs(waypoints) do
				if i > 1 then
					if (waypoints[1].Position - point.Position).Magnitude > 2 then
						if point.Action == Enum.PathWaypointAction.Walk and waypoint == nil then
							waypoint = point
							index = i
						else
							break
						end
					end
				end
			end

			if index then
				local possibleJump = waypoints[index + 1]
				if possibleJump and possibleJump.Action == Enum.PathWaypointAction.Jump and waypoint ~= nil then
					if (waypoint.Position.Y -  possibleJump.Position.Y) > 0 then
						jumpWaypoint = possibleJump
					end
				end
			end
			end

			if waypoint then
				if jumpWaypoint and jumpWaypoint.Action == Enum.PathWaypointAction.Jump then
					local jumpStarted = os.time()
					humanoid:ChangeState(Enum.HumanoidStateType.Jumping)

					local con
					local hasLanded = false

					con = humanoid.StateChanged:Connect(function(old, new)
						if new == Enum.HumanoidStateType.Landed then
							con = nil
						end
					end)

					task.delay(2, function()
						if os.time() - jumpStarted > 2 and con ~= nil then
							con = nil
							print(canJump)
							task.delay(2, function()
								canJump = true
								print(canJump)
							end)
						end
					end)

					humanoid:MoveTo(jumpWaypoint.Position)
					humanoid.MoveToFinished:Wait()
				end
				humanoid:MoveTo(waypoint.Position)
			end
		end
	end
end

You should place waypoints this after the if statement.

1 Like

Didn’t think of that! Hasn’t affected me ever before but I see how it could cause an error, I’ll fix that

I have another issue, so this is no longer relevant

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.