NPC/SetEnemy

From Garry's Mod
(Difference between revisions)
Jump to: navigation, search
(Fixed example nr. 1, since the logic was wrong and did not work...)
m (Replaced #player.GetAll with player.GetCount)
Line 24: Line 24:
  
 
-- Set it here to save processing power...
 
-- Set it here to save processing power...
local _totalAmountOfPlayers = #player.GetAll()
+
local _totalAmountOfPlayers = player.GetCount()
  
 
for i, j in pairs( player.GetAll() ) do
 
for i, j in pairs( player.GetAll() ) do
Line 42: Line 42:
  
 
--
 
--
-- The loop is 100 % finnished before checking...
+
-- The loop is 100 % finished before checking...
 
if (
 
if (
 
i == _totalAmountOfPlayers and
 
i == _totalAmountOfPlayers and

Revision as of 12:26, 13 September 2019

 NPC:SetEnemy( )

Contents

Description

Sets the target for an NPC.

Arguments

Entity enemy

The enemy that the NPC should target

Arguments

boolean newenemy=true

Calls NPC:SetCondition(COND_NEW_ENEMY) if the new enemy is valid and not equal to the last enemy.

Examples

Example

If any NPC has no specific target, it will go towards the nearest enemy. Place this in a think function in init.lua

for k, v in pairs( ents.FindByClass("npc_*") ) do
	if ( v:IsNPC() ) then
		if ( !IsValid( v:GetEnemy() ) ) then
			local nearest_ply           = nil
			local currentLowestDistance = nil

			-- Set it here to save processing power...
			local _totalAmountOfPlayers = player.GetCount()

			for i, j in pairs( player.GetAll() ) do
				local nextDistance = j:GetPos():Distance( v:GetPos() )

				--
				-- Figure out if this Player is closer to the NPC or not
				if (
					j:IsValid() and (
						!currentLowestDistance or
						nextDistance < currentLowestDistance
					)
				) then
					currentLowestDistance = nextDistance
					nearest_ply           = j
				end

				--
				-- The loop is 100 % finished before checking...
				if (
					i == _totalAmountOfPlayers and
					nearest_ply and
					nearest_ply:IsValid()
				) then
					--
					-- Set the enemy
					v:SetEnemy(nearest_ply)
					-- Update the NPC's memory
					npc:UpdateEnemyMemory(nearest_ply, nearest_ply:GetPos())
				end
			end
		end
	end
end


Personal tools
Navigation