Feedback on chaser NPC

my NPC is kind of shoddily made and terribly optimized, and is still kind of stupid, but im wondering; why?
any feedback on this is appreciated

SCRIPT:

local NPC = script.Parent
local NPCHumanoid = NPC.Humanoid
local NPCHumanoidRootPart = NPC.HumanoidRootPart

local function GetNearestPlayer()
	local players = game.Players:GetPlayers()
	local nearestplayer = nil
	local nearestdistance = math.huge
	for _,player in pairs(players) do
		if player.Character and player.Character.HumanoidRootPart then
			local char = player.Character
			local distance = (char.HumanoidRootPart.Position - NPC.HumanoidRootPart.Position).Magnitude
			
			if distance < nearestdistance then
				nearestdistance = distance
				nearestplayer = player
			end
		end
	end
	return nearestplayer,nearestdistance
end

local pathfindingservice = game:GetService("PathfindingService")

local function RaycastToPlayer(player)
	for i=0,30 do
		local rayorigin = NPCHumanoidRootPart.Position
		local raydirection = player.Character.HumanoidRootPart.Position - NPCHumanoidRootPart.Position
		raydirection = Vector3.new(raydirection.X,i-15,raydirection.Z)
		local raycastparams = RaycastParams.new()
		raycastparams.FilterType = Enum.RaycastFilterType.Exclude
		raycastparams.FilterDescendantsInstances = {NPC,game.Workspace.Chasers}
		
		local raycastResult = workspace:Raycast(rayorigin,raydirection,raycastparams)

		if raycastResult and raycastResult.Instance and raycastResult.Instance.Parent and game.Players:GetPlayerFromCharacter(raycastResult.Instance.Parent) then
			return true
		end
	end
	return false
end

local function Move(player,distance)
	local path = pathfindingservice:CreatePath({
		AgentCanClimb = true,
		AgentRadius = 3,
		AgentHeight = 6,
		AgentCanJump = true,
		Costs = {
			Climb = 2  -- Cost of the climbing path; default is 1
		}
	})
	path:ComputeAsync(NPCHumanoidRootPart.Position,player.Character.HumanoidRootPart.Position)
	local velocity = player.Character.HumanoidRootPart.AssemblyLinearVelocity
	
	local waypoints = path:GetWaypoints()
	for i=1,#waypoints do
		print(i)
		local waypoint = waypoints[i]
		print("1")
		if waypoint.Action == Enum.PathWaypointAction.Jump and NPCHumanoid:GetState() ~= Enum.HumanoidStateType.Jumping and NPCHumanoid:GetState() ~= Enum.HumanoidStateType.Freefall then
			NPCHumanoid:ChangeState(Enum.HumanoidStateType.Jumping)
		end
		print("2")
		if RaycastToPlayer(player) then
			print("no wall")
			NPCHumanoid:MoveTo(waypoint.Position + velocity)
			print("no wall2")
			else
			print("wall")
			print(waypoint.Position)
			NPCHumanoid:MoveTo(waypoint.Position)
			print("wall2")
			repeat
				wait()
				print(NPCHumanoidRootPart.AssemblyLinearVelocity.Magnitude)
			until
			NPCHumanoidRootPart.AssemblyLinearVelocity.Magnitude < 7
			print("4")
		end
	end
end

while wait(0.1) do
	local player,distance = GetNearestPlayer()
	if player and player.Character then
		Move(player,distance)
	end
end
1 Like