How to make a PART move to the PLAYER?

Hello I was messing around with pathfinding and I wanted to know how to make an AI chase someone. RIght now I am able to make an AI go to a specific location so I was thinking of like constantly sending the location of the player for the ai to walk to however its not really chasing and instead just going to where the player was previously. \

How do i make the ai chase the player

2 Likes

The usual way to do this is to loop the players in the game, then find the closest character based on distance. You then pathfind to the character and then repeat this cycle every 0.5 seconds or so.

You can use the RunService to repeatedly update the AI’s position towards the player’s position.


-- assume the AI is a child of this script with a humanoid model


local ai = script.Parent
local humanoid = ai.Humanoid

local player = game:GetService("Players").LocalPlayer -- change this to get the player you want to chase
local playerCharacter = player.Character
local playerHumanoid = playerCharacter:WaitForChild("Humanoid")

local RUN_SPEED = 16 -- adjust this to set the AI's running speed

local function updateAI()
    local aiPosition = ai.PrimaryPart.Position
    local playerPosition = playerCharacter.PrimaryPart.Position
    local direction = playerPosition - aiPosition
    direction = Vector3.new(direction.X, 0, direction.Z).Unit -- ignore the Y component of the direction
    humanoid:MoveTo(aiPosition + direction * RUN_SPEED) -- move the AI towards the player at a constant speed
end

game:GetService("RunService").Heartbeat:Connect(updateAI)

this code assumes that the player is always in sight of the AI. If the player goes behind a wall or other obstacle, the AI will continue moving towards the player’s last known position. To handle this case, you could use pathfinding to find a path from the AI’s current position to the player’s current position, or you could use raycasting to check if there are any obstacles between the AI and the player.

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