How to make an NPC Attack after being damaged?

You can write your topic however you want, but you need to answer these questions:
Hey guys, I’m working on a game sort of like combat rift, and can’t seem to figure out how to make an NPC be passive until damaged. Any help?

I have tried using a “script.Parent.HealthChanged:Wait()” but it didnt work, only teleported the NPC onto your head.

My script:

local larm = script.Parent:FindFirstChild("LeftUpperArm")
local rarm = script.Parent:FindFirstChild("RightUpperArm")
script.Parent.HealthChanged:Wait()

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("HumanoidRootPart")
			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
	wait(0.1)
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent:MoveTo(target.Position, target)
	end
end

Anything I should change/fix? Thanks!

This should be fairly easy enough to do with a simple RemoteEvent.

A LocalScript should fire a hit RemoteEvent that is being listened to by the server. The argument should be the part that was hit by whatever weapon was used.

When the event is triggered, do some simple sanity checks on the server to determine if the hit was genuine or not. For example, check how far the player was from the AI and what they used to hit the AI with. This is done just in case the client was an exploiter and tampered with the RemoteEvent.

Once everything checks out and the hit has been verified, invoke a Bindable event in the AI that will retrieve the player object as an argument. From there, you can decide what to do with the information.

Note: RemoteEvent will always have its first argument as the player object that fired the event. So you don’t need to pass in the player information. You just need to pass in the part that was hit.

Here’s a rough layout of how everything works:

2 Likes

that makes a lot of sense, thanks a ton!

1 Like