Please help me understand this script

so i am trying to locate the part where it moves the part’s direction, but i cannot for the life of me find it

-- ㊗
function findTorso(pos)
	local torso = nil
	local dist = 100000
	local child = workspace:children()
	for i=1, #child do
		if child[i].className == "Model" then
			local h = child[i]:findFirstChild("Humanoid")
			if h ~= nil then
				local check = child[i]:findFirstChild("Head")
				if check ~= nil then
					if (check.Position - pos).magnitude < dist then
						torso = check
						dist = (check.Position - pos).magnitude
--around here i think
					end
				end
			end
		end
	end
	return torso
end

game:GetService("RunService").Stepped:Connect(function()
	local torso = findTorso(script.Parent.Position)
	if torso ~= nil then
		script.Parent.CFrame = CFrame.new(script.Parent.Position, torso.Position)
	end
end)

i am not very great at scripting, but i understand some logic, but i do not see any cframe or anything that can move the part, am i missing something?

2 Likes

Are you trying to make the NPC chase the player? Since I saw you require Humanoid to detect it.

1 Like

Perhaps you are referring to this line in the RunService.Stepped event function?

script.Parent.CFrame = CFrame.new(script.Parent.Position, torso.Position)
1 Like

First off, this is extremely old code, I can tell by how its written.

I would highly suggest you look at more refined NPC code, not using deprecated functions such as :children

1 Like

how would i modernize it? i only need the part to face the nearist player at all times

1 Like

i thought it didnt make sense that it is put in a if torso == nil statement because why would it rotate it if the torso is non-existant? anyway, i am trying to find a alternative to cframe because there will be another body force, is there a cframe type that only do rotations? i tried lookat, it didnt work

1 Like
function findTorso(pos)
	local closestDistance = math.huge
	local closestTorso = nil

	local tablePlayers = game:GetService("Players"):GetPlayers()

	for _, plr in pairs(tablePlayers) do
		if plr.Character then
			local Magnitude = (plr.Character.PrimaryPart.Position - pos).Magnitude

			if Magnitude < closestDistance then
				closestDistance = Magnitude
				closestTorso = plr.Character.Torso
			end
		end
	end

	return closestTorso
end

game:GetService("RunService").Stepped:Connect(function()
	local torso = findTorso(script.Parent.Position)
	if torso ~= nil then
		script.Parent.CFrame = CFrame.new(script.Parent.Position, torso.Position)
	end
end)

i was wondering if there is a way to replace the cframe.new with cframes.angles? there will be a bodyposition applied onto the part so they will fight eachother

1 Like