Tap action on Sprite in cocos2d

I want to do an action in my sprites when they touch, this is an action method:

-(void) spriteEffect { CCSprite *actionEffect = avatar; id jump = [CCJumpBy actionWithDuration:1 position: ccp(0, 0) height:50 jumps:1]; id sequence = [CCSequence actions: jump, nil]; [actionEffect runAction:sequence]; } 

Now, my problem is that I do not know how to make the touch act with the sprite; should i use this?

 - (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 

Msps are in the .png image with the assigned .plist.

+4
source share
3 answers
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if ([touch tapCount] == 1) { // Add Your Action } } 

OR

 UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SpriteThouch)]; [[[CCDirector sharedDirector] openGLView] addGestureRecognizer:gr]; 

and method of calling SpriteThouch

 -(void)SpriteThouch { // code here } 
+2
source

I use CCNode + SFGestureRecognizers.h (https://github.com/krzysztofzablocki/CCNode-SFGestureRecognizers) to add gestures to my sprites.

So all you have to do is:

  • import CCNode + SFGestureRecognizers.h

  • add sprite: CCSprite * button = [CCSprite spriteWithCGImage: ....

  • add code for sprite

    button.isTouchEnabled = YES;

    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget: target action: selector];

    [addGestureRecognizer button: tap];

0
source

I usually use CCMenuItemImage when I want to handle simple sprites:

Use the following method to create a menu item:

 itemFromNormalImage:selectedImage:target:selector: 

As you can see, you can pass the image of the menu item (for example, a sprite image), pass the target (usually the ā€œIā€ that implements the action) and, of course, the method (selector) that is called when the menu item has been touched.

If you need more help with this, let me know ...

0
source

All Articles