Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

how to i make an enimy ai walk to the nearest torso?

so i am trying to make a slime (it is one part) move torwards the player

but it doesnt move

note : it doesnt have arms and legs

while wait() do
	dist = 10
	items = game.Workspace:GetChildren()
	
	for i = 1,#items do
		if items[i].ClassName == "Model" then
			torso = items[i]:findFirstChild("Torso")
			if torso ~= nil then
				if (torso.Position - script.Parent.Head.Position).magnitude < dist then

					script.Parent.Humanoid:MoveTo(torso.Position,torso)
					print(torso.Position)

				end
			end
		end
	end
	
end

1 answer

The following script will make the part face towards and move towards the nearest player. This uses body objects so you will need to have the following descendants under the part you want to move.

Part

  • BodyGyro
  • BodyPosition
local part = script.Parent -- Part you want to move

function move(target)
	local dir = (target.Position - part.Position).unit
	local spawnPos = part.Position
	local pos = spawnPos + (dir * 1)
	local speed = 15 -- Change this to the speed you want it to move at
	part:findFirstChild("BodyGyro").cframe = CFrame.new(pos,  pos + dir)
	part:findFirstChild("BodyGyro").maxTorque = Vector3.new(10000,10000,10000)
	part:findFirstChild("BodyPosition").position = target.Position
	part:findFirstChild("BodyPosition").maxForce = Vector3.new(10000, 10000, 10000) *  speed
end

function findNearestTorso(pos)
	local list = game.Workspace:GetChildren()
	local torso = nil
	local dist = 50  -- Change this to the trigger distance
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= part) then
			temp = temp2:findFirstChild("Torso")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0)  then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end

while true do
	local torso = findNearestTorso(part.Position)
	if torso ~= nil then
		move(torso)
	end
	wait()
end

Note: This will keep pushing the player with a lot of force, I suggest adding a debounce that changes when the torso is touched. It will also fly upwards, but this is adjustable by changing the axes involved on the body position's maxForce on line 11.

This discussion is preserved as it was. New answers, comments, and votes are closed.