Tuesday, November 4, 2014

Current project: AI_NPC.lua

This is my AI NPC code.  It's a pretty simple modification of the NPC code to orient the character towards the player, then spit out some text at them when they hit the use key.

ADD TO global.lua:
+ Code Snippet
nsarray = {}
nsarraymaxvalue = 3
nsarray[1]="test1"
nsarray[2]="test2"
nsarray[3]="test3"
ns_def="Default."

FYI, NS=abbreviation for 'npc string'.
As you can see there's an array max value used to define just how many times our loop should cycle.  Then there's a flag passed to an array index via nsarray.  That flag unfortunately for now had to be the health indicator.  I'll work on the code later so the guy won't die when you shoot him (at least easily) but for now this gets the job done.

Then make an AI_NPC piece:

AI_NPC.lua
+ Code Snippet
-- LUA Script - precede every function and global member with lowercase name of script

-- globals
ai_neutral_state = {}

--Mike's Simple NPC script
--You must set the following global variables:
-- nsarraymaxvalue = 3
-- nsarray[1]="test1"
-- nsarray[2]="test2"
-- nsarray[3]="test3"
-- ns_def="default"  
-- Each of these array values correlate to the health of the object.  
-- More can be used.  Default is fallback if it's out of range.


-- init when level first runs
function ai_npc_init(e)
 CharacterControlUnarmed(e)
 ai_neutral_state[e] = "stood"
end

function ai_npc_main(e)
local hastalkedyet
local NPCm
local NPCh 
NPCh = g_Entity[e]['health']

NPCm = nsarraymaxvalue
hastalkedyet = 0

 -- Detect player distance
 PlayerDist = GetPlayerDistance(e)
   
 -- Always looking at player
 if PlayerDist < 200 then
    LookAtPlayer(e)
   if g_KeyPressE == 1 then
    for NPCi=1, NPCm do
        if g_Entity[e]['health'] == NPCi then
            PromptDuration(nsarray[NPCi],1000)
            hastalkedyet = 1
        end
    end
    if hastalkedyet == 0 then 
       PromptDuration(ns_def,1000)
    end
  end
 end
end

Video Example:


Not the best code, I'll admit.  But it does the job.  Enjoy!




No comments:

Post a Comment