2011-10-09 38 views
6

我有一個問題,我根本無法弄清楚;可能是因爲我沒有正確的知識。在Cocos2D中滾動拼貼地圖

我有一個Tiled製作的TMX地圖。該地圖比屏幕尺寸大(地磚是32x32像素,並且有100x100地磚)。 我想要做的是能夠通過滑動屏幕來移動地圖。

我已經看過各種在線教程,並檢查了paddle.m示例,但仍無法使其工作。 我遇到過的所有教程都專注於在地圖上移動一個夾住的居中精靈...... 同樣,我想要做的就是能夠通過滑動/滑動屏幕來移動地圖;就像在滾動iPod或移動圖片時一樣。

任何人都可以幫忙嗎?

這裏是我的ccTouchMoved代碼

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint touchPointMap = [touch locationInView: [touch view]]; 
    touchPointMap = [[CCDirector sharedDirector] convertToGL: touchPointMap]; 
    touchPointMap = [self convertToNodeSpace: touchPointMap]; 
    CCLOG(@"Touch Point Map %lf, %lf", touchPointMap.x, touchPointMap.y); 

    self.position = CGPointMake(touchPointMap.x, touchPointMap.y); 
} 

爲了說明我看到屏幕上的問題,當我使用的代碼上面輕掃屏幕: 看來,如果我觸摸屏幕的中心,地圖的左下角將跳轉到所觸摸的座標,並隨着我的觸摸移動,直到我的觸摸被解除。 地圖的左下角將始終移動到我開始觸摸的位置。 此外,在地圖移動時,它會像瘋狂一樣閃爍,如果移動過度,則會完全消失。

再次感謝所有,非常感謝。 最好和親切的問候, hiro

回答

6

我找到了解決問題的辦法。 Cocos2D社區中有一位非常聰明的人寫了一個控制器,不僅可以有機地平移,而且可以放大和縮小。

Link to Controller, example and preview movie

你不會需要編寫您touchBegan,移動和End方法;這個控制器爲你做這一切。

我的init

self.theMap = [CCTMXTiledMap tiledMapWithTMXFile: @"city_map.tmx"]; 
     self.bgLayer = [theMap layerNamed:@"bg"]; 

     // boundingRect is the area you wish to pan around 
     CGRect boundingRect = CGRectMake(0, 0, 32*50, 16*50); 

     theMap.anchorPoint = ccp(0,0); 
     [self addChild: theMap z: -1]; 

     // _controller is declared in the @interface as an object of CCPanZoomController 
     _controller = [[CCPanZoomController controllerWithNode:self] retain]; 
     _controller.boundingRect = boundingRect; 
     _controller.zoomOutLimit = _controller.optimalZoomOutLimit; 
     _controller.zoomInLimit = 2.0f; 

     [_controller enableWithTouchPriority:0 swallowsTouches:YES]; 
+1

該代碼是現在的cocos2d-擴展的一部分:https://github.com/cocos2d/cocos2d-iphone-extensions – drewish