加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

寻路 A星

发布时间:2020-12-14 17:14:34 所属栏目:百科 来源:网络整理
导读:--寻路 local MAX_ROW_NUM = 9 --行数 local MAX_COL_NUM = 9 --列数 local director = cc.Director:getInstance() local visibleSize = director:getVisibleSize() --小方块宽高 local ItemWidth = visibleSize.width / MAX_COL_NUM local ItemHeight = Ite

--寻路


local MAX_ROW_NUM = 9 --行数
local MAX_COL_NUM = 9 --列数

local director = cc.Director:getInstance()
local visibleSize = director:getVisibleSize()

--小方块宽高
local ItemWidth = visibleSize.width / MAX_COL_NUM
local ItemHeight = ItemWidth

--查找方向
local SEARCH_POS = {
cc.p(-1,0), --左边
cc.p(0,1), --上
cc.p(1, --右
cc.p(0,-1), --下
}

self.m_allItems = {}

for i=1,MAX_ROW_NUM do
self.m_allItems[i] = {}
for j=1,MAX_COL_NUM do
local smallItem = smallItem:create(i,j)
smallItem:setPosition((j - 1) * ItemWidth,(i - 1) * ItemHeight)
self:addChild(smallItem)


self.m_allItems[i][j] = smallItem
end
end

--从(1, 1)找向(7, 7)

self:_AStar(cc.p(1,cc.p(7,7))


function TestLayer:_AStar(from,to)
local queue = {from}

--记录行走的路径
local searchMap = {[from.x*MAX_ROW_NUM + from.y] = {from}}

repeat
local p = table.remove(queue,1)
if(not p) then break end

--将目前格子的周围相邻的格子压栈 for _,point in ipairs(SEARCH_POS) do local x = point.x + p.x local y = point.y + p.y if x > 0 and x <= MAX_COL_NUM and y > 0 and y <= MAX_ROW_NUM then --格子有效范围内 local pp = clone(searchMap[p.x*MAX_ROW_NUM + p.y]) table.insert(pp,cc.p(x,y)) if x == to.x and y == to.y then --找到了 for _,point in pairs(pp) do -- print("x,y: ",point.x,point.y) end return elseif not self.m_allItems[x][y]:_getIsMask() then --格子未寻过 self.m_allItems[x][y]:_setIsMask(true)--标记格子寻路过 table.insert(queue,y)) searchMap[x*MAX_ROW_NUM + y] = pp end end end until false end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读