房西杭头像

NPC动态刷新、定时刷出、超时消失回收

业务规则

  1. 支持两种模式:定点定时刷新、一次性临时NPC(超时自动消失)
  2. 刷新组配置:同组多个NPC,按配置数量、权重随机刷;支持刷新上限(同地图最多存活多少个)
  3. 回收触发:超时到期、地图关闭、服务停服、手动GM回收;回收时清理AI、台词计时器、护送状态、商店临时数据
  4. 刷新冷却:一组刷新完成后,进入冷却,冷却结束才会再次刷新
  5. 互斥:同一个刷新点位同一时间只能存在一个NPC;防止重叠刷出
  6. 持久:刷新组状态(冷却时间、当前存活列表)内存缓存,不需要落库,重启重置

配置表 npc_refresh.csv

字段说明
refresh_group_id刷新组ID
map_id地图ID
pos_list点位数组 {{x,y},{x,y}}
npc_pool候选NPC {{npc_cfg_id,weight},...}
max_spawn本组最大同时存活数量
refresh_cd刷新冷却秒数
alive_timeNPC存活时长(秒),0=永久不自动消失
is_active是否启用该刷新组 0/1

错误码

ErrCode = {
    RefreshGroupNotExist = 15001,
    ReachMaxSpawn = 15002, -- 达到本组最大存活上限
    NoEmptyPos = 15003, -- 没有空闲点位
}

Proto

// NPC刷出同步
message SC_NpcSpawn {
    uint64 npc_uid = 1;
    int32 cfg_id = 2;
    float x = 3;
    float y = 4;
}
// NPC消失回收同步
message SC_NpcDespawn {
    uint64 npc_uid = 1;
}

核心Lua NpcMgr扩展

-- 刷新组缓存
NpcMgr.refresh_group_cfg = {}
-- 刷新组运行时数据 key:group_id
NpcMgr.refresh_runtime = {}
-- key:npc_uid -> group_id 反向映射,快速查NPC属于哪个刷新组
NpcMgr.npc_refresh_bind = {}

-- 加载刷新配置
function NpcMgr:LoadRefreshCfg()
    local rows = CfgMgr:GetAll("npc_refresh")
    for _,row in ipairs(rows) do
        self.refresh_group_cfg[row.refresh_group_id] = row
        self.refresh_runtime[row.refresh_group_id] = {
            next_refresh_tick = 0,
            spawned_npc = {}, -- 存活npc_uid列表
        }
    end
end

-- 从池子按权重随机选npc模板
function NpcMgr:PickNpcFromPool(pool)
    local sum = 0
    for _,item in ipairs(pool) do sum = sum + item.weight end
    if sum <= 0 then return nil end
    local r = math.random(1, sum)
    local acc = 0
    for _,item in ipairs(pool) do
        acc = acc + item.weight
        if r <= acc then
            return item.npc_cfg_id
        end
    end
    return pool[1].npc_cfg_id
end

-- 获取一个空闲点位
function NpcMgr:GetEmptyPos(group_rt, pos_list)
    local occupied = {}
    for _,uid in ipairs(group_rt.spawned_npc) do
        local npc = self:GetNpcByUid(uid)
        if npc then
            occupied[("%d|%d"):format(math.floor(npc.x), math.floor(npc.y))] = true
        end
    end
    for _,pos in ipairs(pos_list) do
        local key = ("%d|%d"):format(math.floor(pos.x), math.floor(pos.y))
        if not occupied[key] then
            return pos
        end
    end
    return nil
end

-- 执行一组刷新
function NpcMgr:DoSpawnGroup(group_id)
    local cfg = self.refresh_group_cfg[group_id]
    local rt = self.refresh_runtime[group_id]
    if not cfg or not rt then return false, ErrCode.RefreshGroupNotExist end
    if #rt.spawned_npc >= cfg.max_spawn then
        return false, ErrCode.ReachMaxSpawn
    end

    local pos = self:GetEmptyPos(rt, cfg.pos_list)
    if not pos then
        return false, ErrCode.NoEmptyPos
    end

    local npc_cfg_id = self:PickNpcFromPool(cfg.npc_pool)
    -- 创建NPC
    local npc = self:CreateNpc(npc_cfg_id, cfg.map_id, pos.x, pos.y)
    if not npc then return false end

    -- 绑定刷新组
    self.npc_refresh_bind[npc.uid] = group_id
    table.insert(rt.spawned_npc, npc.uid)

    -- 设置自动回收计时
    if cfg.alive_time > 0 then
        npc.despawn_time = os.time() + cfg.alive_time
    end
    -- 初始化idle台词计时器
    self:InitNpcTalkTimer(npc)

    -- 同屏广播刷出
    MsgMgr:SendScreen(npc.map_id, npc.x, npc.y, "SC_NpcSpawn", {
        npc_uid = npc.uid,
        cfg_id = npc.cfg_id,
        x = npc.x,
        y = npc.y
    })
    return true
end

-- 回收单个NPC(属于刷新组)
function NpcMgr:DespawnNpc(npc_uid)
    local group_id = self.npc_refresh_bind[npc_uid]
    local npc = self:GetNpcByUid(npc_uid)
    if npc then
        -- 清理护送、台词计时器
        self:EscortFail(self.escort_map[npc_uid])
        self.npc_talk_timer[npc_uid] = nil
        -- 广播消失
        MsgMgr:SendScreen(npc.map_id, npc.x, npc.y, "SC_NpcDespawn", {npc_uid = npc_uid})
        self:RemoveNpc(npc_uid)
    end
    -- 从刷新组存活列表移除
    if group_id and self.refresh_runtime[group_id] then
        local rt = self.refresh_runtime[group_id]
        for i,v in ipairs(rt.spawned_npc) do
            if v == npc_uid then
                table.remove(rt.spawned_npc, i)
                break
            end
        end
    end
    self.npc_refresh_bind[npc_uid] = nil
end

-- Tick 刷新&超时回收,service tick调用
function NpcMgr:TickNpcRefresh(delta)
    local now = os.time()
    for group_id, rt in pairs(self.refresh_runtime) do
        local cfg = self.refresh_group_cfg[group_id]
        if cfg.is_active == 1 then
            -- 冷却到点尝试刷新
            if now >= rt.next_refresh_tick then
                local ok, _ = self:DoSpawnGroup(group_id)
                -- 无论是否成功,重置冷却(也可以改成成功才重置,按需切换)
                rt.next_refresh_tick = now + cfg.refresh_cd
            end
            -- 遍历本组NPC,检查超时回收
            local tmp = {}
            for _,uid in ipairs(rt.spawned_npc) do
                local npc = self:GetNpcByUid(uid)
                if npc and npc.despawn_time and now >= npc.despawn_time then
                    self:DespawnNpc(uid)
                else
                    table.insert(tmp, uid)
                end
            end
            rt.spawned_npc = tmp
        end
    end
end

GM指令

-- 手动触发某个刷新组立刻刷:/npc_spawn_group group_id
CmdMgr:RegisterCmd("npc_spawn_group", function(role, args)
    local gid = tonumber(args[1])
    local ok, err = NpcMgr:DoSpawnGroup(gid)
    if not ok then
        return "刷新失败 err:"..tostring(err)
    end
    return "刷新成功"
end)

-- 清空刷新组全部NPC:/npc_clear_group group_id
CmdMgr:RegisterCmd("npc_clear_group", function(role, args)
    local gid = tonumber(args[1])
    local rt = NpcMgr.refresh_runtime[gid]
    if not rt then return "刷新组不存在" end
    local copy = table.clone(rt.spawned_npc)
    for _,uid in ipairs(copy) do
        NpcMgr:DespawnNpc(uid)
    end
    rt.next_refresh_tick = os.time()
    return "清空本组NPC完成"
end)

坑点清单

  1. tick遍历刷新组不要在每一帧全量扫,量大时分片轮询,降低CPU开销
  2. NPC被玩家打死、脚本删除时,一定要调用 DespawnNpc,清理绑定关系,防止脏数据
  3. 点位重叠判断:建议用格子坐标,不要浮点数直接对比
  4. 临时NPC和常驻NPC分开标记,常驻NPC不进入这套自动回收逻辑
  5. 跨地图切图、地图实例销毁时,批量回收该地图所有刷新NPC

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/u013430094/article/details/171312072

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--