npcManager.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. local npcManager = class("npcManager")
  2. function npcManager:ctor()
  3. self.mNpcsInCurrViewFieldMap = {}
  4. self.mNpcsInCurrViewField = {}
  5. self.mNpcsIndexMap = {}
  6. self.mNpcCount = 0
  7. end
  8. function npcManager:destory()
  9. if npcManager.instance then
  10. npcManager.instance = nil
  11. end
  12. end
  13. function npcManager:Inst()
  14. if not npcManager.instance then
  15. npcManager.instance = npcManager.new()
  16. end
  17. return npcManager.instance
  18. end
  19. function npcManager:AddNpc(npc)
  20. if not npc then
  21. return false
  22. end
  23. local npcID = npc:GetID()
  24. if self.mNpcsInCurrViewFieldMap[npcID] then
  25. return false
  26. end
  27. self.mNpcCount = self.mNpcCount + 1
  28. local n = self.mNpcCount
  29. self.mNpcsIndexMap[npcID] = n
  30. self.mNpcsInCurrViewField[n] = npc
  31. self.mNpcsInCurrViewFieldMap[npcID] = npc
  32. end
  33. function npcManager:RmvNpc(npcID)
  34. local npc = self.mNpcsInCurrViewFieldMap[npcID]
  35. if not npc then
  36. return false
  37. end
  38. self.mNpcsInCurrViewFieldMap[npcID] = nil
  39. local index = self.mNpcsIndexMap[npcID]
  40. if index == self.mNpcCount then
  41. self.mNpcsInCurrViewField[index] = nil
  42. else
  43. -- last index --> index
  44. local lastActor = self.mNpcsInCurrViewField[self.mNpcCount]
  45. self.mNpcsInCurrViewField[index] = lastActor
  46. self.mNpcsIndexMap[lastActor:GetID()] = index
  47. -- reset last value
  48. self.mNpcsInCurrViewField[self.mNpcCount] = nil
  49. end
  50. self.mNpcsIndexMap[npcID] = nil
  51. self.mNpcCount = self.mNpcCount - 1
  52. end
  53. function npcManager:FindNpcIDInCurrViewField()
  54. local recvVec = {}
  55. local num = 0
  56. for i = 1, self.mNpcCount do
  57. local m = self.mNpcsInCurrViewField[i]
  58. if m then
  59. num = num + 1
  60. recvVec[num] = m:GetID()
  61. end
  62. end
  63. return recvVec, num
  64. end
  65. function npcManager:FindOneNpcInCurrViewFieldById(npcID)
  66. return self.mNpcsInCurrViewFieldMap[npcID]
  67. end
  68. function npcManager:GetNpcInCurrViewField()
  69. return self.mNpcsInCurrViewField, self.mNpcCount
  70. end
  71. function npcManager:Cleanup()
  72. self.mNpcsInCurrViewFieldMap = {}
  73. self.mNpcsInCurrViewField = {}
  74. self.mNpcsIndexMap = {}
  75. self.mNpcCount = 0
  76. end
  77. return npcManager