quick中,讓精靈順着tilemap製作的地圖路徑移動

 


製作上述的地圖,在彎道出添加對象。

 

增加地圖類:

 

local tileMap=nil
local map=class("map",
	function()
		return display.newLayer()
	end)


function map:getInstance()
    if tileMap==nil then
    	tileMap=map.new()
    end	
    return tileMap
end

function map:ctor()
    self.tile=CCTMXTiledMap:create("gameMap.tmx")
    self:addChild(self.tile)

   
    self.bgLayer=self.tile:layerNamed("bg")
end

function map:getMapObjectGroup()
    return self.tile:objectGroupNamed("obj")
end    

function map:toTilePosition(param)
	local p={}
    p.x=math.floor(param.x/(self.tile:getTileSize().width))
    p.y=math.floor((self.tile:getMapSize().height*self.tile:getTileSize().height-param.y)/self.tile:getTileSize().height)

    return p
end
function map:toCocosPosition(param)
    local p={}
    p.x=math.floor(param.x*(self.tile:getTileSize().width)-25)
    p.y=math.floor((self.tile:getMapSize().height-param.y)*self.tile:getTileSize().height-25)
   
    return p
end	
return map	


 

在玩家類的ctor中增加:

--獲取對象層中的點
    self.pointArray=self.map:getMapObjectGroup():getObjects()
    self.allPoint={}
    for i=0,self.pointArray:count()-1 do
    
        local valueX = self.pointArray:objectAtIndex(i):objectForKey("x"):intValue()
        local valueY = self.pointArray:objectAtIndex(i):objectForKey("y"):intValue()
        
        j=#(self.allPoint)+1
        self.allPoint[j] = {}
        self.allPoint[j].x=valueX
        self.allPoint[j].y=valueY
    end
  
    --初始化索引
    self.pointIndex=1
    --初始化位置
    self:setPosition(self.allPoint[1].x,self.allPoint[1].y)

    self:entityMove()

 

 


以及增加一個移動的方法:

function entity:entityMove()
    self.pointIndex=self.pointIndex+1
    if self.pointIndex>#self.allPoint then return end
    
    --兩個點的距離
    local moveTime=(self:getPositionX()-self.allPoint[self.pointIndex].x)*(self:getPositionX()-self.allPoint[self.pointIndex].x)+
    (self:getPositionY()-self.allPoint[self.pointIndex].y)*(self:getPositionY()-self.allPoint[self.pointIndex].y)
    moveTime=math.sqrt(moveTime)*0.01

    --local x, y =self:getPosition()
    --print(CCPoint(10,10):getDistance(ccp(x, y)))
    local moveAction=transition.sequence({
            CCMoveTo:create(moveTime,CCPoint(self.allPoint[self.pointIndex].x,self.allPoint[self.pointIndex].y)),
            CCCallFunc:create(handler(self, self.entityMove))
        })

    
    self:runAction(moveAction)



end


 

 

 

實現最終的效果是:

 

 

還有哪裏不明白的?

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章