How can I center a small CCTMXTileMap in cocos2d?

I am making a 2d tile based RPG with cocos2d. I use CCTMXTileMaps for my cards. My player is focused on the screen and the map moves around it (except when the player goes to the edge of the map, where they move away from the center and actually move). This system works well on large maps. However, on small maps, the map is tied to the upper right of the screen. While the mechanics are still working, it would be nice for these small cards to be automatically centered.

How to make cards smaller than screen sizes? I want the card to be concentrated in the red box. (The red box here is for illustrative purposes only; in fact, it does not exist in the code.)

enter image description here

EDIT:

So, I figured out how to do this theoretically, but it's hard for me to understand the coordinate system. I use the following code to center the map, but it does not behave as expected. The map is loading from the screen.

    if ((self.tileMap.contentSize.height < screenSize.height) && (self.tileMap.contentSize.width < screenSize.width)) {

    CGSize winSize = [[CCDirector sharedDirector] winSize];
    CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);        


    CGPoint centerOfMap = CGPointMake((self.tileMap.mapSize.width*self.tileMap.tileSize.width)/2, (self.tileMap.mapSize.height*self.tileMap.tileSize.height)/2);

    self.tileMap.anchorPoint = centerOfMap;
    self.tileMap.position = centerOfView;

}

What am I doing wrong here?

+5
source share
1 answer

Well, the solution is quite simple, although I missed a few things. The most basic code for centering a map in a parent element:

    //
    //  Get the center of the 
    //  screen/map layer (which are the same)
    //

    CGPoint centerOfSelf = CGPointMake(self.contentSizeInPixels.width/2, self.contentSizeInPixels.height/2);

    //
    //  Position the map in the center
    //

    tileMap.position = CGPointMake(centerOfSelf.x - (tileMap.contentSizeInPixels.width/2), centerOfSelf.y - (tileMap.contentSizeInPixels.height/2));

, . , ( ) "" , , - -. , , , , "" , . "" . , , "world scene", . :

//
//  Reset the size of the bounding
//  area so that we can properly 
//  center maps that are smaller than
//  the bounding area of the screen.
//

CGSize screenSize = [[CCDirector sharedDirector] winSize];
self.contentSizeInPixels = screenSize; 

//move camera
self.position = CGPointZero;

, "" 0,0, .

0

All Articles