Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
-3

AI Targets only one person, even though I'm in range?

Asked by 7 years ago
Edited 7 years ago

My friend and I were testing this AI for a game we're making, but since he was the person who got in his range first, the AI would only target him, but then even after my friend respawns, the AI doesn't target me, even though I'm in his range.

EDIT: I have removed the script because it was answered. My problem was I was returning nil too early.

0
Why remove the script? It's good to keep it for reference. P100D 590 — 7y

1 answer

Log in to vote
1
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
7 years ago

Problem

You're returning nil too early in your findNearestTorso function. When the first player joins the server, that will be the only player targeted. If that player is not within 25 studs of the AI, the function will return nil not checking the other players.


Solution

Return nil after the for loop has finished. That way all players are processed, and the AI may confirm no one is within range.


Final Script

function findNearestTorso()
    for _, plr in pairs(game.Players:GetChildren()) do
        while not plr.Character do wait() end
        if plr.Character:findFirstChild("Humanoid") then
            if (trooper.Torso.Position - plr.Character.Torso.Position).magnitude <= 25 then
                return plr.Character.Torso
            --else
            end
        end
    end
    return nil --Just move return nil to here. It's clear no one is within range at this point.
end

Hopefully this answered your question. If it did, do not forget to hit the accept answer button. If you have any questions, feel free to ask them in the comments below.
Ad

Answer this question