Nome: Guard
Tipo: NPC
Autor: Oneshot
Muitos devem conhecer o NPC Guard, que possui inteligência artificial e ataca jogadores que possuem skulls de servidores que baixam.
Acontece que o script desse NPC foi programado apenas para um NPC só, então quando você tenta, por exemplo, ter dois Guards no servidor, se um está na cidade A e outro na cidade B e, por exemplo, o NPC da cidade A começa atacar um jogador, o NPC da cidade B se teleporta "magicamente" para a cidade A.
Pensando nisso, resolvi otimizar todo o código, orientando ele a objetos. Isso faz com que cada NPC (objeto) tenha suas próprias variáveis e não compartilhem mais elas entre si.
Em data/npc/lib, crie um arquivo chamado guard.lua e adicione o conteúdo abaixo:
Guard = {
config = {
attackspeed = 1000,
},
combat = {type = COMBAT_PHYSICALDAMAGE, min = 100, max = 200}
}
function Guard:new()
local ret = {}
setmetatable({}, {__index = self.combat})
setmetatable(ret, {__index = self})
return ret
end
function Guard:reset()
self.config = Guard.config
self.target = 0
selfFollow(0)
doTeleportThing(self.id, self.position)
end
function Guard:updateTarget()
if self.target ~= 0 then
return
end
local creatures = getSpectators(getThingPosition(self.id), self.range, self.range, false)
for i = 1, #creatures do
local target = creatures[i]
if isCreature(target) and not isNpc(target) and getCreatureSkull(target) >= 3 then
if not getTilePzInfo(getThingPosition(target)) then
if selfFollow(target) then
selfSay("I don't tolerate people like you, ".. getCreatureName(target))
self.target = target
self:attack()
break
end
end
else
self:reset()
end
end
end
function Guard:attack()
if self.target == 0 then
self:reset()
return
end
self.time = self.time or os.clock()
if self.time < os.clock() then
if getDistanceBetween(getThingPosition(self.id), getThingPosition(self.target)) == 1 then
doTargetCombatHealth(self.id, self.target, self.combat.type, -self.combat.min, -self.combat.max, CONST_ME_DRAWBLOOD)
end
self.time = self.time + (self.config.attackspeed/1000)
end
end
Agora em data/npc/scripts, crie um arquivo chamado guard.lua e adicione o conteúdo abaixo:
local guard = Guard:new()
function onCreatureAppear(cid)
if cid == getNpcId() then
guard.id = getNpcId()
guard.target = 0
guard.position = getNpcPos()
end
end
function onCreatureDisappear(cid)
if cid == guard.target then
guard:reset()
end
end
function onCreatureSay(cid, type, msg)
return false
end
function onThink()
guard:updateTarget()
if guard.target ~= 0 then
if isCreature(guard.target) then
guard:attack()
else
guard:reset()
end
else
guard:reset()
end
end
E em data/npc/ crie um arquivo chamado guard.xml e adicione o conteúdo abaixo:
<?xml version="1.0" encoding="UTF-8"?>
<npc name="Guard" script="guard.lua" walkinterval="0" speed="200" floorchange="0">
<health now="100" max="100"/>
<look type="134" head="57" body="59" legs="40" feet="76" addons="0"/>
<parameters/>
</npc>
Abraços \o