>Scrolling Menus on Cocos2D
>A short time ago I was working on a scene within a new game I’m writing. This scene required the display of a variable length list of items that could be tapped.
I soon found that the CCMenu class didn’t really support the concept of scrolling, and after much hunting around I decided that I’d have to do it myself.
The end result is a small, reusable class that accepts 4 parameters:
- The name of a background image.
- The name of a foreground image.
- A CGRect that defines the area within which the menu will appear.
- An array of NSString objects that form the menu item labels.
The code to create and display a menu is as simple as:
- (void) showScrollingMenu:(CCMenuItemLabel*)item {
ScrollingMenuScene *ns =
[ScrollingMenuScene nodeWithForeground:@"foreground.png"
andBackground:@"background.png"
andRect:CGRectMake(50.0, 40.0, 200.0, 260.0)
andItems:[NSArray arrayWithObjects:
@"First", @"Second", @"Third", @"Fourth",
@"Fifth", @"Sixth", @"Seventh", @"Eighth",
@"Ninth", @"Tenth", @"Eleventh", @"Twelfth",
@"Thirteenth", @"Fourteenth", @"Fifteenth", @"Sixteenth",
@"Seventeenth", @"Eighteenth", @"Nineteenth", @"Twentieth",
nil]];
[[CCDirector sharedDirector] replaceScene:ns];
}
To achieve the appearance of a scrolling menu, the class places the background at the bottom, a layer above this containing the menu, and the foreground image on top.
It is assumed that the foreground image has a transparent “window” that matches the rectangular area defined by the CGRect parameter.
You can get the code, and a sample project that demonstrates it from www.pkclsoft.com/downloads/ScrollingMenuSample.zip
As it turned out, I didn’t end up using the class in my project, but it’s handy to have it around. At the moment it only uses textual menu items, but there’s no reason why it couldn’t be adapted to use other menu item classes.