Aligning CCMenu to a grid

前端 未结 5 1453
星月不相逢
星月不相逢 2021-01-14 07:38

Does anybody know the best practice approach to getting an array of CCMenuItems to align to a grid? This is a cocos2d question

For example :

int lev         


        
5条回答
  •  天涯浪人
    2021-01-14 08:37

    Ok, while not as flexible as I would like, I've got a decent enough solution for my purposes. Anyone else can feel free to use this code if they too find it useful.

    //////// Put images (or whatever) for all levels in an array /////////        
    
        int levelCount = 15;
        NSMutableArray* menuArray = [NSMutableArray arrayWithCapacity:levelCount];
        for (int x = 1; x<=levelCount; x++) {
    
            CCLOG(@"Creating level icon for Level %i", x);
    
            CCMenuItemImage* item = [CCMenuItemImage itemFromNormalImage:@"Button2n.png" 
                                                           selectedImage:@"Button2s.png" 
                                                                  target:self 
                                                                selector:@selector(onPlay:)];
            [menuArray addObject:item];                        
        }
    

    //////// arrange in a grid with specific number of columns /////////

        CGSize screenSize = [CCDirector sharedDirector].winSize;
    
        int columns = 5;
    
        int spaceBetweenColumns = columns + 1;
    
        int spacing = screenSize.width / spaceBetweenColumns;
    
        CCLOG(@"screenWidth (%f) / columnsWithEdges (%i) = spacing = %i, ", screenSize.width, spaceBetweenColumns, spacing);
    
        CGPoint currentDrawPoint = CGPointMake(0, screenSize.height - spacing);  // start at the top 
    
        for (CCMenuItem *item in menuArray) {
    
            currentDrawPoint.x = currentDrawPoint.x + spacing;
    
            if (currentDrawPoint.x > (columns * spacing)) {
                // start a new line as we have reached the end of the previous one
                currentDrawPoint.x = spacing;
                currentDrawPoint.y = currentDrawPoint.y - spacing;
            }
    
            item.position = currentDrawPoint;
            [self addChild:item];
    
        }
    

提交回复
热议问题