Now that the bot is complete you will want to add it to the
NPC spawn tab. Pretty easy, but here is the code used for this tutorial
anyways:
list.Set( "NPC", "simple_nextbot", {
Name =
"Simple bot",
Class =
"simple_nextbot",
Category
= "NextBot"
} )
When you use this just replace both "simple_nextbot"
with the file name of the bot and the rest is pretty easy to figure out
yourself.
Challenges
You now have a basic bot running around the map and that's
pretty much it. Here are some things you can try on your own to spice it up:
Search for more then just players
Play sounds when its wandering around.
Only search for enemies that are in front of it, not all
around.
Make it hide if the enemy is holding a shotgun.
Stop chasing the enemy when it's really close and do a melee
attack.
The full code
AddCSLuaFile()
ENT.Base =
"base_nextbot"
ENT.Spawnable =
true
function ENT:Initialize()
self:SetModel(
"models/hunter.mdl" )
self.LoseTargetDist = 2000 --
How far the enemy has to be before we lose them
self.SearchRadius
= 1000 -- How far to search for enemies
end
----------------------------------------------------
-- ENT:Get/SetEnemy()
-- Simple functions used in keeping our enemy saved
----------------------------------------------------
function ENT:SetEnemy( ent )
self.Enemy
= ent
end
function ENT:GetEnemy()
return
self.Enemy
end
----------------------------------------------------
-- ENT:HaveEnemy()
-- Returns true if we have a enemy
----------------------------------------------------
function ENT:HaveEnemy()
-- If
our current enemy is valid
if (
self:GetEnemy() and IsValid( self:GetEnemy() ) ) then
--
If the enemy is too far
if
( self:GetRangeTo( self:GetEnemy():GetPos() ) > self.LoseTargetDist ) then
--
If the enemy is lost then call FindEnemy() to look for a new one
--
FindEnemy() will return true if an enemy is found, making this function return
true
return
self:FindEnemy()
--
If the enemy is dead( we have to check if its a player before we use Alive() )
elseif
( self:GetEnemy():IsPlayer() and !self:GetEnemy():Alive() ) then
return
self:FindEnemy() --
Return false if the search finds nothing
end
--
The enemy is neither too far nor too dead so we can return true
return
true
else
--
The enemy isn't valid so lets look for a new one
return
self:FindEnemy()
end
end
----------------------------------------------------
-- ENT:FindEnemy()
-- Returns true and sets our enemy if we find one
----------------------------------------------------
function ENT:FindEnemy()
--
Search around us for entities
-- This
can be done any way you want eg. ents.FindInCone() to replicate eyesight
local
_ents = ents.FindInSphere( self:GetPos(), self.SearchRadius )
-- Here
we loop through every entity the above search finds and see if it's the one we
want
for k,
v in pairs( _ents ) do
if
( v:IsPlayer() ) then
--
We found one so lets set it as our enemy and return true
self:SetEnemy(
v )
return
true
end
end
No comments:
Post a Comment