I was creating an NPC to implement into my game, so I made this script in which the NPC will fire their tool so that the bullet travels towards you:

local player = game.Players.LocalPlayer or game.Players.PlayerAdded:Wait()
player.CharacterAdded:Connect(function(character)
	while not character do
		character.AncestryChanged:Wait()
	end
	
	local hrp = character:WaitForChild('HumanoidRootPart')
	local hum = character:WaitForChild('Humanoid')
	local enemyHum = script.Parent.EnemyHum
	local enemyHRP = script.Parent.HumanoidRootPart
	
	local xOffset = enemyHRP.Parent.RightUpperArm.RightShoulder.C0.X
	local yOffset = enemyHRP.Parent.RightUpperArm.RightShoulder.C0.Y
	local zOffset = enemyHRP.Parent.RightUpperArm.RightShoulder.C0.Z
	
	local enemyHRPcf = enemyHRP.Position
	local dead = false
	local inRange = false
	hum.Died:Connect(function()
		dead = true
	end)
	while wait() do
		if (enemyHRP.Position - hrp.Position).Magnitude < 30 then
			if hum.Health > 0 then
				inRange = true
				script.Parent.Pistol.Handle.fire:Play()
				enemyHRP.CFrame = CFrame.new(enemyHRP.Position, hrp.Position)
				enemyHRP.Parent.RightUpperArm.RightShoulder.C0 = CFrame.new(xOffset,yOffset,zOffset) * CFrame.Angles(math.rad(hrp.Orientation.X + 45),0.2,0) * CFrame.Angles(math.rad(hrp.Orientation.X + 45),0.2,0)
				local bulletPart = workspace.bullet:Clone()
				bulletPart.Parent = workspace
				bulletPart.Position = script.Parent.Pistol.Handle.Position
				bulletPart.Transparency = 0
				bulletPart.Anchored = true
				bulletPart.CanCollide = false
				bulletPart.Orientation = (script.Parent.Pistol.Handle.Orientation - hrp.Position) + Vector3.new(90,270,0)
				for i = 0,25,0.5 do
					bulletPart.CFrame = bulletPart.CFrame * CFrame.new(0,0,i)
					wait()
					bulletPart.Touched:Connect(function(hit)
						local t = true
						if hit.Parent:WaitForChild('Humanoid') then
							if t == true then
								t = false
								hum:TakeDamage(50)
								bulletPart:remove()
							end
						end
					end)
				end
				bulletPart:remove()
			elseif (enemyHRP.Position - hrp.Position).Magnitude > 30 then
				inRange = false
			end
		end
	end
end)

Yes, I know. It's long and boring but I really need help. I don't know any built-in functions that is related to a NPC model's humanoid being added or whatever.

Help please!

2 comments

0

Why are you referecing LocalPlayer on a Server Script?

0

No clue where is the problem, but instead of using 2 if statements back to back, you can use "and" between both conditions.