1. 程式人生 > >quick中,讓精靈順著tilemap製作的地圖路徑移動

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

實現最終的效果是:

還有哪裡不明白的?