I am attempting to make a basic game which requires a serious of buttons to control player movement. Keep in mind I am using cocos-2d. My goal is to have the buttons be holdable and move a sprite when held down. The code i am using now looks like this.
CCMenuItemHoldable.h
@interface CCMenuItemSpriteHoldable : CCMenuItemSprite {
bool buttonHeld;
}
@property (readonly, nonatomic) bool buttonHeld;
CCMenuItemHoldable.m
@implementation CCMenuItemSpriteHoldable
@synthesize buttonHeld;
-(void) selected
{
[super selected];
buttonHeld = true;
[self setOpacity:128];
}
-(void) unselected
{
[super unselected];
buttonHeld = false;
[self setOpacity:64];
}
@end
and for the set up of the buttons
rightBtn = [CCMenuItemSpriteHoldable itemFromNormalSprite:[CCSprite spriteWithFile:@"art/hud/right.png"] selectedSprite:[CCSprite spriteWithFile:@"art/hud/right.png"] target:self selector:@selector(rightButtonPressed)];
CCMenu *directionalMenu = [CCMenu menuWithItems:leftBtn, rightBtn, nil];
[directionalMenu alignItemsHorizontallyWithPadding:0];
[directionalMenu setPosition:ccp(110,48)];
[self addChild:directionalMenu];
This all seems to work fine but when i do
-(void)rightButtonPressed:(id) sender
{
if([sender buttonHeld])
targetX = 10;
else{
targetX = 0;
}
}
The crash has been fixed but I am trying to get my sprite to move. In my game tick function I add the value of targetX to the position of the sprite on a timer, still no movement.
Please, always include a crash log when asking questions about crashes.
In your case, I can guess the problem. You are adding this selector:
Your method is called
Which would be, as a selector,
rightButtonPressed:– note the colon indicating that an argument is passed. Either change the method so it has no argument, or add a colon to the selector when you create the button.The crash log would be telling you this – it would say “unrecognised selector sent to…” with the name of the receiving class, and the name of the selector.