思路
利用scrollview的滚动控件来实现地图的拖拉滚动。我这边大地图直接用一张大图通过sprite创建出来然后addChild到scrollview,可根据项目需求自己酌情考虑,反正最终是要添加到scrollview滚动容器里。不多说,上代码
local _MIN_SCROLL_SCALE = 1.0 --缩放最小尺寸
local _MAX_SCROLL_SCALE = 2.0 --缩放最大尺寸
local layer = cc.Layer:create() --创建layer
local sprite = cc.Sprite:create("home.png") --创建地图
sprite:setAnchorPoint(0,0) --设置锚点
local scrollView = cc.ScrollView:create(display.size) --滚动容器用来放置大地图
scrollView:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH) --设置滚动方向
scrollView:setDelegate()
scrollView:setBounceable(false) --关闭回弹效果
scrollView:setMinScale(_MIN_SCROLL_SCALE) --设置最小缩放尺寸
scrollView:setMaxScale(_MAX_SCROLL_SCALE) --设置最大缩放尺寸
scrollView:setContentSize(sprite:getContentSize()) --设置大小
scrollView:setZoomScale(_MIN_SCROLL_SCALE) --设置缩放
scrollView:setSwallowTouches(false) --点击事件吞噬
scrollView:addChild(sprite) --地图添加到滚动容器
layer:addChild(scrollView,0) --滚动容器添加到layer
self:addChild(layer) --layer添加到界面
--缩放监听
scrollView:registerScriptHandler(function ( ... )
print("zoomScale:"..scrollView:getZoomScale())
end, cc.SCROLLVIEW_SCRIPT_ZOOM)
--双击判定。
local isDoubleClick = false
--触摸回调函数 参数1为触摸类型 参数2为多点触摸的数组表
local function onTouchEvent(eventType,touchs)
--touchs:多点触摸数组表。
--大小 = n点触摸*3
--touchs[1] : x点坐标
--touchs[2] : y点坐标
--touchs[3] : id号
if #touchs >= 4 then
print("多点触摸!!!!!!!!")
if eventType=="began" then
self.distance = math.abs(cc.pGetDistance(cc.p(touchs[1],touchs[2]),cc.p(touch[4],touchs[5])))
elseif eventType=="moved" then
self.newDistance = math.abs(cc.pGetDistance(cc.p(touchs[1],touchs[2]),cc.p(touch[4],touchs[5])))
local scals = self.newDistance/self.distance * _MIN_SCROLL_SCALE
scrollView:setZoomScale(scals)
self.distance = self.newDistance
end
else
print("单点触摸!!!!!!!!")
if eventType=="began" then
if isDoubleClick then
-- dump("double click")
isDoubleClick = false
scrollView:setZoomScale(_MIN_SCROLL_SCALE)
else
self.scheduler = cc.Director:getInstance():getScheduler():scheduleScriptFunc(function ()
if isDoubleClick then
-- dump("single click")
isDoubleClick = false
end
if self.scheduler then
cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.scheduler)
self.scheduler = nil
end
end, 0.25 , false)
isDoubleClick = true
end
end
end
end
layer:setTouchEnabled(true)
layer:registerScriptTouchHandler(onTouchEvent,true)
本文介绍如何在Cocos2d-x中利用ScrollView的滚动控件实现大地图的拖动和缩放功能。通过设置缩放比例、触摸事件监听和双击缩放等操作,详细讲解了地图拖动的实现过程。

1601

被折叠的 条评论
为什么被折叠?



