简体   繁体   中英

Cocos2d : scale layer to a sprite

I'm having a bit of a problem solving this trivially-looking feature. In my game, at some point in a level, I stop the main game loop and want to zoom to the player sprite. The player sprite is added to a layer that contains this loop and run the code to zoom to this player.

It looks like this :

-(void) stopGameAndZoomToPlayer {
    [gamePlayLoop_ invalidate];

    zoomToPlayerLoop_ = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(tickZoomToPlayerLoop:) userInfo:nil repeats:YES];
}

The tick method, is for now implemented like this :

-(void) tickZoomToPlayerLoop:(NSTimer*)timer {
    if (self.scale > 4) {
        [zoomToPlayerLoop_ invalidate];
    }
    [self setScale:self.scale+0.001];   

    CGSize winSize =  [[CCDirector sharedDirector]winSize]; 
    CGPoint targetPosition = playerSprite_.position;

    float wantedX = ((winSize.width/2-targetPosition.x)/self.scale);
    float wantedY = ((winSize.height/2-targetPosition.y)/self.scale);
    CGPoint maximumCenter = ccp(wantedX,wantedY);

    [self setPosition:maximumCenter];     
}

Seems trivial right ? Yet, there's something I must be missing because the zoom, while slow, is offset vis-a-vis the player sprite. The player sprite, at the end of the tickZoomToPlayerLoop timer, appears in the top right corner of the screen ; it is not in the center (but not even centered of the top right corner of the viewport).

The way I see it, this code put the center of the main layer to the position of the player sprite. Then it scales . Actually the position shouldn't be in the zoom loop but I put it here because I'll need to handle the boundaries of the level layer, because as for now the user can see the black void of non playable zone, outside the level. Yet, even if the center of the main layer at the beginning of the loop seems to be the player sprite, when scaling, one can see it is not.

Does the scale is targeted to the center of a CCNode ? Is it offseted in any way ? Does the anchor point plays a part in the way the scaling is done ?

Some more infos :

  • the anchor point of the main layer is (0.5,0.5) - the default one
  • the position of the main layer is, at first before the timer, (0,0) - simply added when creating the scene

Scaling to my knowledge is effected by anchor points. If all you need to do is zoom in way not use CCCamera?

[myLayer.camera setEyeX:0 eyeY:0 eyeZ:zoomValue];

You can change the eyeZ to zoom in and out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM