A Simple CCSprite Button in Cocos2d
CCSprite’s can implement the
<CCTargetedTouchDelegate>
protocol and implement the ccTouchBegan:
, ccTouchEnded:
, ccTouchMoved:
and ccTouchCancelled:
methods. I’ve built a class called GTButton
that does this and allows you to specify two sprites to toggle between when the touch occurs. By default you must release your finger in the CCSprite to run a selector (a method on a target object), but you can change this with mustRelease
mustReleaseInside boolean properties of the GTButton
object. Here’s the header file and the download link to the sample project. Remember to change the target SDK in the project settings to the latest one on your Xcode install - I used 5.0.
#import "cocos2d.h" typedef enum buttonState { FMButtonSelected, // Finger Down FMButtonUnselected // Finger Up } FMButtonState; @interface GTButton : CCSpriteDownload Sample Project{ FMButtonState state; CCSprite *spriteSelected, *spriteUnselected; id target; SEL selector; /* mustRelease means you must lift your finger anywhere on screen to perform the selector. mustReleaseInside is subset of mustRelease and means you must lift your finger inside sprite. */ BOOL mustRelease, mustReleaseInside; } @property (assign,readwrite,nonatomic) id target; @property (assign,readwrite,nonatomic) SEL selector; @property (assign,readwrite,nonatomic) BOOL mustReleaseInside, mustRelease; +(GTButton*) buttonWithUnselectedSprite:(CCSprite*)theSpriteUnselected SelectedSprite:(CCSprite*)theSpriteSelected Target:(id)theTarget Selector:(SEL)theSelector; -(id) initWithUnselectedSprite:(CCSprite*)theSpriteUnselected SelectedSprite:(CCSprite*)theSpriteSelected Target:(id)theTarget Selector:(SEL)theSelector; -(void) setTextureFromSprite:(CCSprite*)sprite; -(void) setSelected:(BOOL)selected; -(BOOL) containsTouchLocation:(UITouch *)touch; // Rect relative to the anchorPoint -(CGRect) relRect; @end