Making an NPC fight back
From VbGORE Visual Basic Online RPG Engine
VBGore comes with several NPC AIs already installed. AI number 2 makes the NPC walk around in a random pattern. If the NPC is hostile then it will attack players, but if it is not hostile it will not fight players, even when it has been attacked.
In this tutorial I'll show you how to modify AI number 2 so that NPCs defend themselves when attacked.
All of the following modifications take place in GameServer.vbp.
Contents |
Declare a new variable
In the Delclares module search for NPCList() As NPC. Just above it should be all of the variables for the NPC. Place the following code just before where it says 'THESE ARRAYS MUST STAY DOWN HERE AT THE BOTTOM OF THE UDT!:
<vb> BaseStat(1 To NumStats) As Long 'Declares the NPC's stats ModStat(FirstModStat To NumStats) As Long 'Declares the NPC's stats
'Begin new code: Attacked As Byte 'If the NPC was attacked 'End new code
'THESE ARRAYS MUST STAY DOWN HERE AT THE BOTTOM OF THE UDT! VendItems() As Obj 'Information on the item the NPC is vending </vb>
Detect the attack
In the NPCs module, in the NPC_AI Sub, add this line to Case 2:
<vb> '*** Random movement *** Case 2
'Attack If NPCList(NPCIndex).Hostile Then b = NPC_AI_Attack(NPCIndex)
'Begin new code If NPCList(NPCIndex).Attacked Then b = NPC_AI_Attack(NPCIndex) 'End new code </vb>
Tell the NPC to fight back
In Function User_AttackNPC in the Users module, add this line:
<vb> 'Calculate hit Hit = Server_RandomNumber(UserList(UserIndex).Stats.ModStat(SID.MinHIT), UserList(UserIndex).Stats.ModStat(SID.MaxHIT)) Hit = Hit - (NPCList(NPCIndex).ModStat(SID.DEF) \ 2) If Hit < 1 Then Hit = 1 Log "User_AttackNPC: Hit (damage) value calculated (" & Hit & ")", CodeTracker '//\\LOGLINE//\\
'Begin new code: NPCList(NPCIndex).Attacked = 1 'End new code </vb>
This will make the NPC fight back when someone hits it. If you also want to make them hostile when hit by a range weapon add this code to Private Sub User_Attack_Ranged in the Users module:
<vb> 'Play the sound of no weapon attacking SfxID = UnequiptedSwingSfx
End If
'Begin new code: NPCList(TargetIndex).Attacked = 1 'End new code
'Get the new heading NewHeading = Server_FindDirection(UserList(UserIndex).Pos, TargetPos) UserList(UserIndex).Char.Heading = NewHeading UserList(UserIndex).Char.HeadHeading = NewHeading </vb>
Clear the variable when respawning
You need to add the following code to the Sub NPC_Spawn in the NPCs module or the NPC will continue attacking the player after it had respawned:
<vb> 'Set vars NPCList(NPCIndex).Pos = TempPos NPCList(NPCIndex).Counters.BlessCounter = 0 NPCList(NPCIndex).Counters.ProtectCounter = 0 NPCList(NPCIndex).Counters.StrengthenCounter = 0 NPCList(NPCIndex).Counters.WarCurseCounter = 0 NPCList(NPCIndex).Flags.NPCAlive = 1 'Begin new code: NPCList(NPCIndex).Attacked = 0 'End new code </vb>
Go back to Adding NPC AIs