Creating Virtual Controller in Cocos-2d
**ATTENTION**
I am currently not so sure if there is a better way to do, but I found this way handy and good for now.
I am currently creating an iPhone game using cocos-2d, iphone game library, and I wanted to create a overlay buttons. I found it's easy using 'Menu' of cocos-2d, because they have animation buttons and it's easy to adjust their positions, align and opacity.
Problem is, they don't have "Button Down" event. So I create a child class of MenuItem to catch their button-down-event by overriding selected/unselected methods.
Here is "VirtualButton.h".
and here is "VirtualButton.m'.
To use this component, code is like
I am currently not so sure if there is a better way to do, but I found this way handy and good for now.
I am currently creating an iPhone game using cocos-2d, iphone game library, and I wanted to create a overlay buttons. I found it's easy using 'Menu' of cocos-2d, because they have animation buttons and it's easy to adjust their positions, align and opacity.
Problem is, they don't have "Button Down" event. So I create a child class of MenuItem to catch their button-down-event by overriding selected/unselected methods.
Here is "VirtualButton.h".
#import
#import "cocos2d.h"
@interface VirtualButton : MenuItemImage {
id myTarget;
SEL selectedCallback;
BOOL pushed;
}
- (void) setOnClickCallback:(id)target selectedCallback:(SEL)selected_cb;
- (void) selected;
- (void) unselected;
@end
and here is "VirtualButton.m'.
#import "VirtualButton.h"
@implementation VirtualButton
- (void) setOnClickCallback:(id)target selectedCallback:(SEL)selected_cb
{
myTarget = target;
selectedCallback = selected_cb;
pushed = NO;
}
- (void) selected
{
[super selected];
if(isEnabled) {
pushed = YES;
[myTarget performSelector:selectedCallback withObject:self];
}
}
-(void) unselected
{
[super unselected];
if(pushed){
pushed = NO;
}
}
-(BOOL) isPushed //To know if button is pressed.
{
return pushed;
}
@end
To use this component, code is like
-(id) init //initializer of virtual control pad layer.
{
MenuItem *leftButton = [VirtualButton itemFromNormalImage:@"left_up.png" selectedImage:@"left_down.png" target:self selector:@selector(leftButtonUpCallback:)];
Menu *menu = [Menu menuWithItems: leftButton, nil];
[(VirtualButton*)leftButton setOnClickCallback:self selectedCallback:@selector(leftButtonDownCallback:)];
[leftButton setPosition:ccp(0, 50.0f)];
[self addChild:menu];
}
-(void) leftButtonUpCallback:(id)sender
{
.... do mouse down event
}
Comments