Scrolling a Tiled Map in Cocos2D
Asked Answered
S

1

6

I've got an issue that I simply can't figure out; probably because I don't have the correct knowledge.

I have a TMX map made in Tiled. The Map is bigger than the screen size (tiles are 32x32pixels and there are 100x100 tiles). What I want to do is to be able to move the map by swiping the screen.

I've looked at various tutorials online and examined the paddle.m example but still can't get it to work. All the tutorials I've come across all focus on moving a clamped centered sprite around a map... Again, what I want to do is to be able to move the map by swiping/sliding the screen; much like when scrolling through your iPod or moving a picture around.

Can anyone help?

Here is my ccTouchMoved code

-(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);
}

To illustrate the problem I'm seeing on screen when I swipe the screen using the code above: It seems that if I touch the center of the screen, the bottom left corner of the map will jump to that touched coordinate and will move with my touch until my touch is lifted. The Map's bottom left corner will always move to where I begin my touch. Also while the map is being moved, it flashes like crazy and if moved excessively, disappears entirely.

Thanks again All, much appreciated. Best and Kind Regards, hiro

Salmons answered 9/10, 2011 at 0:3 Comment(0)
S
6

I found the solution to the problem. There's a very bright person in the Cocos2D community who has written a controller to not only pan around organically, but zoom in and out.

Link to Controller, example and preview movie

You wont need to write your touchBegan, Moved and End methods; this Controller does it all for you.

My 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];
Salmons answered 9/10, 2011 at 11:34 Comment(1)
That code is now part of the cocos2d-extensions: github.com/cocos2d/cocos2d-iphone-extensionsMeacham

© 2022 - 2024 — McMap. All rights reserved.