Hello there!
It’s my first time using OOP and just learning the ropes of things. Anywho, I’m creating a BaseModule for all of the enemies inside of my game which will contain “general” AI (Basically just functions/AI all or the majority of enemies will share like pathfinding).
Anyway, I’m done finishing a function inside of the BaseModule which contains a function that finds the nearest player and allows the NPC using said function to pathfind towards their target depending on what type of enemy the NPC is. (Walkers will move normally while slimes hop towards their target.)
The issue however is that there might be a possible data leak on the BaseModule, more specifically on the pathfinding function I mentioned earlier. It seems to be stuck on walls despite using Roblox’s PathfindingService. (And for insult to injury, it also seems to ignore the player entirely until it reaches the players original position before moving towards the players new position.)
--//Services\\--
local PLRS = game:GetService("Players")
local PFS = game:GetService("PathfindingService")
--//Module\\--
local BaseNPCModule = {}
--//Pathfinding\\--
--All enemy types will be able to use this function
function BaseNPCModule.SetTargetting(Character,Type)
local RootPart = Character.PrimaryPart
local Humanoid = Character.Humanoid
--//Getting all players
local function FindNearestTarget()
local players = {};
local nearest = math.huge;
local target = nil;
for _, player in pairs(PLRS:GetPlayers()) do
local character = player.Character;
if character == nil then
continue;
end;
local distance = (character.HumanoidRootPart.Position - RootPart.Position);
if distance.Magnitude <= nearest then
table.insert(players,{
Magnitude = distance.Magnitude,
Player = player,
});
end;
end;
for _, entry in pairs(players) do
local magnitude = entry.Magnitude;
local Player = entry.Player;
if magnitude < nearest then
nearest = magnitude;
target = Player;
end;
end;
return target;
end
--//Targetting
while task.wait() do
--Getting the player first before doing the pathfinding stuff
local Player = FindNearestTarget()
if Player == nil then
return
end
local Player_Char = Player.Character or Player.CharacterAdded:Wait()
local Char_Root = Player_Char and Player_Char.PrimaryPart
--The actual pathfinding stuff :D
if Type == "Walker" then
local Path = PFS:CreatePath()
Path:ComputeAsync(RootPart.Position, Char_Root.Position)
if Path.Status == Enum.PathStatus.Success then
for _, Waypoint in pairs(Path:GetWaypoints()) do
Humanoid:MoveTo(Waypoint.Position)
Humanoid.MoveToFinished:Wait()
end
end
end
end
end
return BaseNPCModule